嵌套tph继承成员的ef-core负载集合属性 [英] ef-core load collection property of nested tph inherited member
本文介绍了嵌套tph继承成员的ef-core负载集合属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下类结构
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的显式加载,但是它感觉不对。有没有更优雅的解决方案?
What is the best way to query parent data to include information about the children's offshore accounts?. I came up with the solution below, using ef-core's explicit loading, but it just doesn't feel right. 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();
}
}
推荐答案
目前没有办法在父查询中完成,但是可以通过使用 Entry
, Collection $ c的组合来改进显式加载$ c>,
调用:查询
,包含
/ ThenInclude
code>加载
Currently there is no way to accomplish that in the parent query, but the explicit loading can be improved by 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();
这篇关于嵌套tph继承成员的ef-core负载集合属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文