Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In entity framework code first is there a way to add paging to navigation collections?

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?

like image 754
Jason Avatar asked Apr 30 '12 04:04

Jason


People also ask

What difference does AsNoTracking () make?

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.

How does pagination work in C#?

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.

What is eager loading in Entity Framework?

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.

How do I filter data in Entity Framework?

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.


1 Answers

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();
like image 115
Ladislav Mrnka Avatar answered Oct 06 '22 00:10

Ladislav Mrnka