Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selective eager loading in Entity Framework

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.

like image 871
Ofer Avatar asked Mar 22 '10 12:03

Ofer


People also ask

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.

What is the difference between eager and lazy loading in Entity Framework?

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.

Which of the following can be used to eager load data from database in Entity Framework?

Eager loading is achieved using the Include() method.

Which is better lazy loading or eager loading?

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.


1 Answers

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

like image 79
Nate Zaugg Avatar answered Oct 24 '22 20:10

Nate Zaugg