嵌套tph繼承成員的ef-core load collection屬性

c# entity-framework entity-framework-core linq tph

給出以下類結構

 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; }
    }

查詢父數據以包含有關子女離岸賬戶的信息的最佳方法是什麼?我想出了下面的解決方案,使用ef-core的顯式加載,但它感覺不對。有更優雅的解決方案嗎?

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();
            }
     }

一般承認的答案

目前在父查詢中無法實現這一點,但可以通過使用EntryCollectionQueryInclude / ThenIncludeLoad調用的組合來改進顯式加載:

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();

熱門答案

在當前的EFCore(2.1.1)中,您可以在ThenInclude使用類型轉換來獲取您正在尋找的結果:

var parent = _context.Set<Parent>()
                 .Include(x => x.Children)
                 .ThenInclude(y => (y as RichChild).OffshoreAccounts)
                 .SingleOrDefault();


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow