Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an "in" query in entity framework?

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 Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' method, and this method cannot be translated into a store expression.

like image 451
NotDan Avatar asked Jul 16 '09 14:07

NotDan


People also ask

How do I write a query in Entity Framework?

SQL Query for a specific entity type We can use SQLQuery() method to write SQL queries which return an entity object. Example: //DbContext. DbPersonnesEntities db = new DbPersonnesEntities();

How do I get query generated by Entity Framework?

To view the SQL that will be generated, simply call ToTraceString() . You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query.

How do I write queries in EF core?

You can compose on top of the initial raw SQL query using LINQ operators. EF Core will treat it as subquery and compose over it in the database. The following example uses a raw SQL query that selects from a Table-Valued Function (TVF). And then composes on it using LINQ to do filtering and sorting.

Can you execute T SQL statements using Entity Framework?

Entity Framework allows you to execute raw SQL queries for the underlying relational database.


1 Answers

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: I have found some workarounds for this issue - please see WHERE IN clause?:

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:

like image 146
Andrew Hare Avatar answered Sep 29 '22 01:09

Andrew Hare