Ef-core load collection property of the tested inherited nested element

Given the following class structure

public class Parent { public Guid Id { get; public List<BaseChild> Children { get; set; } } public abstract class BaseChild { public int Id { get; set; } public string ChildName { get; set; } } public class NormalChild : BaseChild { public DateTime BirthDate { get; set; } } public class RichChild : BaseChild { public List<OffshoreAccount> OffshoreAccounts { get; set; } } public class OffshoreAccount { public string AccountNumber { get; set; } public AccountInfo AccountInfo { get; set; } } 

What is the best way to request parental data to include information on offshore credential children? I came up with a solution below using explicit ef-core loading, but that just is not the case. Is there a more elegant solution?

 var parent = Context.Set<Parent>() .Where(o => o.Id == Guid.Parse(parentId)) .Include(o => o.Children) .SingleOrDefault(); foreach (var child in parent.Children.OfType<RichChild>()) { Context.Entry<RichChild>(child).Collection(f => f.OffshoreAccounts).Load(); foreach (var account in child.OffshoreAccounts) { Context.Entry<OffshoreAccount>(account).Reference(f => f.AccountInfo).Load(); } } 
+7
c # linq entity-framework entity-framework-core tph
source share
1 answer

There is currently no way to accomplish this in the parent query, but explicit loading can be improved using a combination of Entry , Collection , Query , Include / ThenInclude and Load calls:

 var parent = Context.Set<Parent>() .Where(o => o.Id == Guid.Parse(parentId)) .Include(o => o.Children) .SingleOrDefault(); Context.Entry(parent).Collection(e => e.Children) .Query().OfType<RichChild>() .Include(e => e.OffshoreAccounts) .ThenInclude(e => e.AccountInfo) .Load(); 
+5
source share

All Articles