If I have a Blog entity with a BlogEntries collection which may have hundreds of entries, is there a way to add any server-side paging functionality with EF code first? For example if I do a typical .Skip(x).Take(y) like you would on a DbSet, will it lazy load the entire collection and page it in memory?
AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.
The C# pagination logic is contained in a single Pager class that takes the following constructor arguments: totalItems (required) - the total number of items to be paged. currentPage (optional) - the current active page, defaults to the first page. pageSize (optional) - the number of items per page, defaults to 10.
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog.
To filter data, use linq. You can not use Filter property of BindingSource when the underlying list is BindingList<T> ; Only underlying lists that implement the IBindingListView interface support filtering. To remove filter, just set the data source of your binding source to the local storage of your entities again.
If you query directly DbSet
you can use Take and Skip and it will indeed execute paging on database server (these method calls are translated to SQL). So this works as expected:
// Loads only 10 expected entries through Linq-to-entities
var entries = context.BlogEntries.OrderBy(e => e.Date).Skip(10).Take(10);
Beware that paging navigation properties on loaded entity doesn't work this way:
var blog = context.Blogs.First();
// Lazy loading always loads all related entries and executes ordering and
// paging through Linq-to-objects!
var entires = blog.BlogEntries.OrderBy(e => e.Date).Skip(10).Take(10);
If you want to get paging on navigation property you must use explicit loading
var blog = context.Blogs.First();
var dbEntry = context.Entry(blog);
// This is the way to use Linq-to-entities on navigation property and
// load only subset of related entities
var entries = dbEntry.Collection(b => b.BlogEntries)
.Query()
.OrderBy(e => e.Date)
.Skip(10)
.Take(10)
.Load();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With