【问题标题】:EF Core - checking existence of child [duplicate]EF Core - 检查孩子的存在[重复]
【发布时间】:2020-04-27 04:16:18
【问题描述】:

带有 SQL Server 后端的 EF Core。父实体包含一组子实体。在特定情况下,我对整个子集合不感兴趣,只对是否存在任何子的信息感兴趣——我想避免从数据库中检索整个集合。在 T-SQL 中,我可以使用带有 count 的子查询或带有 TOP(1) 的 CROSS APPLY,但是如何在 EF 中实现呢?

假设模型如下所示(代码不完整):

class Invoice
{
  DateTime InvoiceDate { get; set; }
  Customer Customer { get; set; }
  int CustomerId { get; set; }
  ...
  ...
  ICollection<InvoicePosition> Positions { get; set; }
}

internal virtual DbSet<Invoice> InvoiceSet { get; set; }

我是这样读取数据的:

var invoices = context.InvoiceSet
  .Include(i => i.Customer).ThanInclude(c => c.Country)
  .Where(i => ...)
  .OrderBy(i => ...)
  .Skip(...).Take(...)
  .AsAsyncEnumerable();

await foreach (var invoice in invoices)
{ ... }

我可以包含职位并检查是否存在,但如何在数据库端执行此操作?

编辑: 我需要 InvoiceSet 中的其他属性 - bool HasPositions:

class Invoice
{
  DateTime InvoiceDate { get; set; }
  Customer Customer { get; set; }
  int CustomerId { get; set; }
  ...
  bool HasPositions { get; set; }
  ...
  ICollection<InvoicePosition> Positions { get; set; }
}

如何获取这个新属性的数据?如果可以通过 Linq Query 完成,请提供一个示例,如何将我的阅读方法转换为查询。

【问题讨论】:

  • 你不能用任何你喜欢的Where() 条件检查context.InvoicePositionSet 吗?既然可以直接访问数据,为什么还要间接访问它们?
  • 我需要带有附加信息的发票列表 - 是否存在任何职位。

标签: c# ef-core-3.1


【解决方案1】:
.Where(i => i.Positions.Any())

【讨论】:

  • 我不想以这种方式过滤结果。如果有任何相关职位,我需要所有带有信息的发票。
猜你喜欢
  • 2016-09-29
  • 2021-10-06
  • 2017-10-24
  • 2018-01-25
  • 2016-09-18
  • 2014-07-19
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多