Harald Coppoolse
Harald Coppoolse

Reputation: 30454

Entity Framework Query Items with Id from IEnumerable

Using Entity Framework Code First I have a DbSet of Customers, each customer has a CustomerId:

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

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

All fairly standard.

Somehow I have selected a large sequence of customerIds as an IEnumerable. I want to query all customers with this customerId, to do some heavy LINQ stuff with the selected customers. So I need something like:

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

However, using Enumerable.Contains results in a SQL IN statement, which can't be used if the collection is large.

So what to do if you have a collection of Ids and you want to get an IQueryable of elements with that Id?

Addition: After thinking about it, this question is a bit hypothetical. Normally you don't have thousands of Ids locally, unless they are the result of a query and thus representable in an IQueryable. So although it would be nice to know how to do this, I guess I'm doing something wrong if I really would need it.

Upvotes: 0

Views: 1935

Answers (2)

Lucian Bumb
Lucian Bumb

Reputation: 2881

IEnumerable<int> customerIdsToProcess = ...

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

you can use Join to retrieve all customers which have the CustomerId in customerIdsToProcess

in the above example, you need to call ToList(), other wise you cannot use selectedCustomers for future manipulation, ouside of using.

Upvotes: 1

shady youssery
shady youssery

Reputation: 440

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

Upvotes: 1

Related Questions