In entity framework, how do you perform a "in" query?

.net c# entity-framework linq

Question

How do I choose rows with keys from a list using a select in Linq to Entities? Possibly 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 attempted the Contains technique that was suggested in several of the responses, but it did not work and produced the following exception:

The method "Boolean Contains[Int32](System.Collections.Generic.IEnumerable'1[System.Int32], Int32)" is not supported by LINQ to Entities, thus it cannot be converted into a store expression.

1
49
4/6/2010 9:37:52 PM

Accepted Answer

Try this:

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

Edit: Please refer to WHICH clause? for any solutions I have discovered for this problem.

The Entity Framework does not currently support collection-valued parameters ('statusesToFind' in your example). To work around this restriction, you can manually construct an expression given a sequence of values using the following utility method:

43
7/16/2009 4:24:29 PM

Popular Answer

I had the similar issue and came up with this solution.

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow