Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1, Code-First: Eager loading of cascading collections

If I have the following class model ...

public class A
{
    public int AId { get; set; }
    public ICollection<B> BCollection { get; set; }
}

public class B
{
    public int BId { get; set; }
    public ICollection<C> CCollection { get; set; }
}

public class C
{
    public int CId { get; set; }
}

... is it possible to eager-load an object of type A from the database with all cascading collections included?

I can include the BCollection like so:

A a = context.ASet.Where(x => x.AId == 1)
          .Include(x => x.BCollection)
          .FirstOrDefault();

Can I also include somehow the CCollection of all loaded B objects so that I get A with all dependent objects in memory with a single database query?

like image 552
Slauma Avatar asked Mar 21 '11 13:03

Slauma


People also ask

How do I enable 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. Include is an extension method in the System.

What is eager loading in EF core?

Eager loading means that the related data is loaded from the database as part of the initial query. Explicit loading means that the related data is explicitly loaded from the database at a later time.

What is lazy loading and eager 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 variable declaration would apply eager loading when querying data?

Eager loading is achieved using the Include() method. In the following example, it gets all the students from the database along with its standards using the Include () method.


1 Answers

Use .Include(x => x.BCollection.Select(b => b.CCollection)) also described here.

It works also for cascade. Every time you need to eager load navigation property which is collection use .Select.

like image 131
Ladislav Mrnka Avatar answered Oct 05 '22 22:10

Ladislav Mrnka