Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do a SQL style 'IN' statement in LINQ to Entities (Entity Framework) if Contains isn't supported?

I'm using LINQ to Entities (not LINQ to SQL) and I'm having trouble creating an 'IN' style query. Here is my query at the moment:

var items = db.InventoryItem
                .Include("Kind")
                .Include("PropertyValues")
                .Include("PropertyValues.KindProperty")
                .Where(itm => valueIds.Contains(itm.ID)).ToList<InventoryItem>();

When I do this however, the following exception is thrown:

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

Does anyone have a workaround or another solution for this?

like image 870
JC Grubbs Avatar asked Nov 30 '08 07:11

JC Grubbs


People also ask

Does LINQ work with Entity Framework?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database.

Which join is not supported in LINQ?

LINQ does not support full outer joins directly, the same as right outer joins.

How use not in LINQ query in C#?

Except operator are designed to allow you to query data which supports the IEnumerable<T< interface. Since all LINQ query expressions, and most LINQ queries, return IEnumerable<T<, these operators are designed to allow you to perform set operations on the results of a LINQ query.

Is Entity Framework same as LINQ to SQL?

LINQ to SQL allow you to query and modify SQL Server database by using LINQ syntax. Entity framework is a great ORM shipped by Microsoft which allow you to query and modify RDBMS like SQL Server, Oracle, DB2 and MySQL etc.


1 Answers

You need to either use this one:

.Where(string.Format("it.ID in {0}", string.Join(",", valueIds.ToArray())));

or construct the WHERE part dynamically, as in this post.

P.S. - Information has been updated and this answer updated as follows to maintain relevance:

The link referenced contains the following update:

...in EF4 we added support for the Contains method and at least in this specific case for collection-valued parameters. Therefore this kind of code now works right out of the box and it is not necesary to use any additinal expression building method:

var statusesToFind = new List<int> {1, 2, 3, 4};
var foos = from foo in myEntities.Foos
           where statusesToFind.Contains(foo.Status)
           select foo;
like image 144
liggett78 Avatar answered Oct 22 '22 16:10

liggett78