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?
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.
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.
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. In the following example, it gets all the students from the database along with its standards using the Include () method.
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
.
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