views:

1039

answers:

3

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?

+1  A: 

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.

liggett78
I noticed that even by passing in the where as a string, an IN gets converted to many OR statements..
borisCallens
A: 

Someone had created an expression for this scenario...I found it and hijacked it but can't remember where I found the original source. I'll post the code in a bit. For now this is a marker for me to come back.

Mike Brown
A: 

My workaround is to convert the entities result to a List and after that apply the Contains().

Example:

var items = db.InventoryItem
                .Include("Kind")
                .Include("PropertyValues")
                .Include("PropertyValues.KindProperty")
                .ToList()
                .Where(itm => valueIds.Contains(itm.ID));
Stef
That's awful, sometimes I really hate the hoops EF makes you jump through to do things. But it works for, just looks bad in the code.Thanks
Ryan ONeill
In fact this "workaround" takes all data from the database and filters it in C#. If you have a lot of data, it would effectively bring performance down.
ovolko