2016-11-29 89 views
0

是否可能在實體框架核心(或7)中加載表中沒有相關記錄的所有記錄表?EF.Core加載在其他表中沒有相關記錄的所有記錄

在我的情況下,我有一個Customers表和一個Contracts表。客戶可以有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查詢?

回答

2

你只需要一個LINQ查詢來實現你想要的是這樣的(獨立的EF版本):

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

當然,我認爲在你的客戶實體CustomerId被稱爲Id

+0

謝謝你,所以簡單和工程就像一個魅力 –

0

Customer類添加屬性List<Contracts>,您可以通過下面的查詢獲得客戶未平倉合約:

var customersWithZeroContract = db.Customers.Where(c => c.Contracts.Count() == 0); 
相關問題