views:

1098

answers:

2

How can I do a select in linq to entities to select rows with keys from a list? Something like this:

var orderKeys = new int[] { 1, 12, 306, 284, 50047};
var orders = (from order in context.Orders 
              where (order.Key in orderKeys) 
              select order).ToList();
Assert.AreEqual(orderKeys.Count, orders.Count);

I tried using the Contains method as mentioned in some of the answers but it does not work and throws this exception:

LINQ to Entities does not recognize the method 'Boolean ContainsInt32' method, and this method cannot be translated into a store expression.

+4  A: 
Andrew Hare
This does not work, see edit above.
NotDan
Perhaps you can look into these workarounds: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/
Andrew Hare
+2  A: 

Unfortunately the EF can't translate the queries others have suggested. So while those queries would work in LINQ to Objects, they won't work in LINQ to Entities.

So the solution is a little more involved.

However I have a blog post on this exact topic here. Essentially the solution is to use a little expression tree magic to build an big OR expression.

Hope this helps

Alex

Alex James