2016-08-04 37 views
0

使用實體框架代碼首先我有客戶的DbSet,每個客戶都有一個客戶編號:ID爲實體框架查詢項目自IEnumerable

public class Customer 
{ 
    public int CutomerId {get; set;} 
    ... 
} 

public class MyDbContext : DbContext 
{ 
    public DbSet<Customer> Customers {get; set; 
} 

所有相當標準。

不知何故,我選擇了一系列customerIds作爲IEnumerable。我想用這個customerId來查詢所有客戶,以便與選定的客戶進行一些沉重的LINQ工作。所以,我需要這樣的東西:

IEnumerable<int> customerIdsToProcess = ... 
using (var myContext = new MyDbContext()) 
{ 
    IQueryable<Customer> selectedCustomers = myContext.Customers 
     .Where(customer => customerIdsToProcess.Contains(customer.customerId); 

然而,使用在SQL語句中,如果集合很大,不能使用Enumerable.Contains結果。

那麼如果你有一個ID集合並且你想得到一個帶有該ID的元素的IQueryable,該怎麼辦?

加法:想過之後,這個問題有點假設。通常情況下,本地沒有數千個ID,除非它們是查詢的結果,因此可用IQueryable表示。所以,儘管知道如何做到這一點很好,但如果我真的需要它,我想我會做錯事。

+0

如何分割你的列表,根據列表獲取查詢,然後結合查詢? –

回答

1
IQueryable<Customer> selectedCustomers = myContext.Customers 
    .Where(customer => customerIdsToProcess.Any(x=>x.customerId==customer.customerId)); 
1
IEnumerable<int> customerIdsToProcess = ... 

using (var myContext = new MyDbContext()) 
{ 
    var selectedCustomers = myContext.Customers 
     .Join(customerIdsToProcess,x=>x.CustomerId, y=>y,(x,y)=>x).ToList(); 
} 

可以使用Join檢索這些都是CustomerIdcustomerIdsToProcess

在上面的例子中

,你需要調用ToList()所有的客戶,其他的聰明人,你不能使用selectedCustomers爲未來的操作,using的外側。