【发布时间】:2021-06-19 11:26:04
【问题描述】:
我在查询中遇到了一系列 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 属性位于合成级别。
当我检查生成的 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
}
【问题讨论】:
-
请分享模型。
-
请同时分享实际异常
标签: c# postgresql entity-framework-core npgsql