如何解决Entity Framework Core (Postgres) Multiple Includes 创建 ghost 属性
我在查询中遇到了一系列 Include/ThenInclude 的问题。
这是我的 EntityFrameworkCore 查询:
var fund = await funds.Where(x => x.Id == fundId)
.Include(f => f.Compositions.Where(compo => compo.Date == compositionDate))
.ThenInclude(c => c.CompositionItems)
.ThenInclude(item => item.Asset)
.FirstOrDefaultAsync(token)
?? throw new NotFoundException(nameof(Fund),fundId);
我收到“CompositionDate 不存在”错误。 如您所见,CompositionDate 属性位于 Compositions 级别。
当我检查生成的 SQL 时,我在子查询 Select 语句中得到了这个:
SELECT f1."CompositionFundId",f1."CompositionDate",f1."AssetId",f1."Amount",a."Id",a."CountryCode",a."Currency",a."FundCompositionDate",a."FundCompositionFundId",a."Isin",a."Name",a."SecurityType",a."Ticker",a."Coupon",a."GicsSector",a."InvestmentCase",a."IpoDate",a."Theme"
FROM "FundCompositionItem" AS f1
INNER JOIN "Asset" AS a ON f1."AssetId" = a."Id"
这 2 个属性 a."FundCompositionDate",a."FundCompositionFundId" 在“资产”级别不存在。 它们存在于父级中(在第一个 Include 的“Where”级别)。
我正在为 EFcore 使用 Postgres 提供程序。这可能是问题吗?
我应该使用选择匿名类型 .Select(x => new { Fund = x,Compo = x.Compo.Where(...),etc... }
吗?
如果可能,我想保留导航属性。 (从 compositionItems 访问资产)
任何帮助将不胜感激。
编辑: Atiyar 要求的模型:
public class Portfolio : AuditableEntity
{
public Guid Id { get; set; }
public Guid Name{ get; set; }
}
public class Fund : Portfolio
{
// Irrelevant properties
public IList<FundComposition> Compositions { get; } = new List<FundComposition>();
}
public class FundComposition
{
public Fund Fund { get; set; }
// Primary key / Foreign key
public Guid FundId { get; set; }
// Primary Key
public DateTime Date { get; set; }
public List<FundCompositionItem> CompositionItems { get; set; } = new();
}
public class FundCompositionItem
{
public FundComposition Composition { get; set; }
// Primary Key
public Guid CompositionFundId { get; set; }
// Primary Key
public DateTime CompositionDate { get; set; }
public Asset Asset { get; set; }
// Primary Key
public Guid AssetId { get; set; }
public double Amount { get; set; }
}
public class Asset : BaseEntity
{
// Primary Key
public Guid Id { get; set; }
public string Name { get; set; }
public string Currency { get; set; }
// more properties
}
解决方法
根据我的经验,我先应用了 Include()
和 ThenInclude()
,然后再应用 any 条件子句。我也不确定在包含方法中使用 Where
是否符合您的预期。
您也可以在 .FirstOrDefaultAsync()
的第一个参数中应用您的条件。
var fund = await funds.Where(x => x.Id == fundId)
.Include(f => f.Compositions)
.ThenInclude(c => c.CompositionItems)
.ThenInclude(item => item.Asset)
.FirstOrDefaultAsync(x =>
x.Id == fundId && x.Compositions.Any(compo => compo.Date == compositionDate),token
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。