【问题标题】:EF.Core load all records that don't have a related record in other tableEF.Core 加载其他表中没有相关记录的所有记录
【发布时间】:2016-11-29 09:16:25
【问题描述】:

是否可以在 Entity Framework Core(或 7)中从一个表中加载在另一个表中没有相关记录的所有记录?

在我的例子中,我有一个客户表和一个合同表。客户可以有 0 到 N 个合同。在这个特定的用例中,我想查询所有没有合同的客户。

**Customer Table:**

CustomerId | Name
---------- | ----------
1          | Apple
2          | Google
3          | Microsoft

**Contracts Table:**

| ContractId | CustomerId | StartDate  | EndDate    |
| ---------: | ---------: | ---------- | ---------- |
| 1          | 2          | 01-01-2016 | 01-01-2018 |
| 2          | 3          | 01-01-2016 | 01-01-2018 |

在这种情况下,我希望查询只返回一个包含 Apple 客户的对象。

在 SQL 中,我会这样做:

select cust.CustomerId, cust.Name
  from dbo.Customers as cust
    left outer join dbo.Contracts as contr
      on cust.CustomerId = contr.CustomerId
  where contr.ContractId is null;

如何将其转换为 EF 查询?

【问题讨论】:

    标签: c# sql-server entity-framework


    【解决方案1】:

    你只需要一个 linq 查询来实现你想要的这样(独立于 EF 版本):

    var result = yourContext
        .Customers
        .Where(x => !yourContext.Contracts.Any(y => x.Id == y.CustomerId));
    

    当然我假设在您的客户实体中CustomerId 被称为Id

    【讨论】:

      【解决方案2】:

      Customer类中添加属性List<Contracts>,你可以通过如下查询得到没有合同的客户:

      var customersWithZeroContract = db.Customers.Where(c => c.Contracts.Count()  == 0);
      

      【讨论】:

        猜你喜欢
        • 2015-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        相关资源
        最近更新 更多