Is it possible to limit the number of associated entities eagerly loaded with Include?
e.g. I have Author and Book entities with a many-to-one relation I'd like to load all authors and their last book
Thanks.
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.
While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.
Eager loading is achieved using the Include() method.
Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere. Use Lazy Loading when you are using one-to-many collections. Use Lazy Loading when you are sure that you are not using related entities instantly.
You can't do it using the .Include syntax but you can do it using projection.
var list = (from a in data.Authors
select new
{
Author = a,
Books = (from b in a.Books select b).Take(1)
}).ToList();
When you get the result the materializer will have used it's relationship fixup and you will be able to use list.Author.Books.
see my question at: LINQ to Entities (Entity Framework) Join and .Include conflict
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