2015-09-04 65 views
1

我希望獲得包括幾個屬性的客戶集合,其中包括地址但只有當它尚未被刪除時(SuppressionDate == null在帶有倍數的linq查詢中使用.Include()中的.Where()子句包括

IQueryable<Customer> customers = 
    context.Persons.OfType<Customer>() 
     .Include(customer => customer.Addresses) 
     .Include(customer => customer.Bills) 
     .Include(customer => customer.Code) 
     .Include(customer => customer.Tutors); 

我曾嘗試多種方法來使用WHERE子句以過濾地址:

... 
.Include(customer => customer.Addresses.Where(a => a.SuppressionDate == null)) 
.Include(customer => customer.Bills) 
... 

那是我第一次嘗試,但它會引發以下異常:

System.ArgumentException:包含路徑表達式必須引用在該類型上定義的 導航屬性。對於 參考導航屬性使用虛線路徑,對於集合 導航屬性使用Select運算符。參數名稱:路徑

我也嘗試用相同的where子句在Include()結束,並在查詢結束,但既不似乎工作。

我目前使用的是通過客戶的訪問集合一種變通方法,並刪除被刪除這樣的地址:

foreach(Customer c in customers){ 
    customer.Addresses = customer.Addresses.Where(a => a.SuppressionDate == null).ToList(); 
} 

是相當新的LINQ to對象/實體,我在想,如果有一個內置的方法來實現這一點。

+0

返回的異常是什麼? –

+0

添加了例外 – WizLiz

+0

請嘗試看看https://msdn.microsoft.com/en-gb/data/jj574232.aspx#explicitFilter它提供了有關該類型過濾的一些信息 –

回答

0

如果你得到一個單一的客戶,你可以使用顯式裝載這樣的:

var customer = context.Persons 
    .OfType<Customer>() 
    .Include(customer => customer.Bills) 
    .Include(customer => customer.Code) 
    .Include(customer => customer.Tutors) 
    .FirstOrDefault(); //or whatever 

context.Entry(customer).Collections(x => x.Addresses).Query().Where(x => x.SuppressionDate == null).Load(); 

,使一個很好的查詢和兩個簡單​​的調用數據庫。但在這種情況下,您正在獲取客戶的列表(或集合或其他),並且沒有快捷方式。您的「解決方法」可能會導致數據庫的大量討論。

所以你可能就必須把它一步步時間:

//1. query db to get customers 
var customers = context.Persons 
    .OfType<Customer>() 
    .Include(customer => customer.Bills) 
    .Include(customer => customer.Code) 
    .Include(customer => customer.Tutors) 
    .ToList(); 

//2. make an array of all customerIds (no db interation here) 
var customerIds = customers.Select(x => x.CustomerId).ToArray(); 

//3. query db to get addresses for customers above 
var addresses = context.Addresses.Where(x => customerIds.Contains(x.CustomerId).ToList(); 

//4. assign addresses to customers (again, no db chatter) 
foreach (var customer in customers) 
{ 
    customer.Addresses = addresses 
     .Where(x => x.CustomerId == customer.CustomerId && x.SuppressionDate == null) 
     .ToList(); 
} 

不太bad-仍然只是兩個查詢數據庫。