.Include(...) is not the right solution to load 1:n relationships
When I read about what people suggest to load 1:n relations, it makes me wonder if they know what they are doing. In Entity Framework Core, basically every LINQ expression translates into one SQL statement. When you do Include(...) on 1:n relationships (collection navigation properties), you are basically creating a cross-product of children and parent items.
Example:
public class A
{
public long Id { get; set; }
public ICollection<B> Bs { get; set; }
}
public class B
{
public ICollection<C> Cs { get; set; }
}
public class C
{
}
//somewhere in your code, you query the DbSet:
var result = this.Set<A>().Where(a => a.Id == 42).Include(a => a.Bs).ThenInclude(b => b.Cs).ToList();
Let's say for this A you have 10 Bs and each B has 10 Cs. The resulting SQL query will return 100 result rows which are pretty wide because they include all properties of A, B and C. In this example this might not be a big problem, but imagine every A, B or C has like tens or hundreds of properties, or some very big fields. This can add up to a lot of unnecessary overhead really fast.
Unfortunately, Entity Framework Core doesn't offer another solution than just manually load collection properties afterwards. You can do this for every single object by using the entity entry, like that:
private void LoadCollections(A obj)
{
var entityEntry = dbContext.Entry(obj);
foreach (var collection in entityEntry.Collections)
{
if (collection.IsLoaded)
{
continue;
}
collection.Load();
if (collection.CurrentValue != null)
{
foreach (var child in collection.CurrentValue)
{
LoadCollections(child);
}
}
}
}
This is not the ultimate solution, of course. I just wanted to show how it could work in general. It always depends on your data model or problem.
It would be nice to have some built-in feature in Entity Framework Core to generally load a complete object graph for a couple of objects at once. They could add some optimizations like loading collections for multiple parents at once.