In entity structure code, is there first a way to add paging to the navigation collection?

If I have a blog entry with a BlogEntries collection that can contain hundreds of posts, is there a way to add server-side paging features with EF code in the first place? For example, if I make a typical .Skip (x) .Take (y), as you would on a DbSet, will it be too lazy to load the entire collection and print it in memory?

+7
source share
1 answer

If you request DbSet directly, you can use Take and Skip and it will actually do the swap on the database server (these method calls translate to SQL). Thus, 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 the swap navigation properties on a loaded object do not work as follows:

 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 for the 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(); 
+14
source

All Articles