EF核心-检查孩子的存在

时间:2020-04-26 18:44:41

标签: c# ef-core-3.1

带有SQL Server后端的EF Core。父实体包含子代的集合。在特定情况下,我对整个子集合不感兴趣,仅对是否有子存在的信息不感兴趣-我想避免从数据库中检索整个集合。在T-SQL中,我可以将带有count或CROSS APPLY的子查询与TOP(1)一起使用,但是如何在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查询完成此操作,请提供一个示例,说明如何将我的阅读方法转换为查询。

1 个答案:

答案 0 :(得分:0)

.Where(i => i.Positions.Any())