Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a "where in values" in LINQ-to-Entities 3.5

Tags:

Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work:

var values = new[] { "String1", "String2" };  // some string values

var foo = model.entitySet.Where(e => values.Contains(e.Name));

I believe this works in LINQ-to-SQL though? Any thoughts?

like image 957
Ty. Avatar asked Sep 17 '08 22:09

Ty.


2 Answers

Update: found out how to do this. And EF will generate the appropriate SQL on the database. I'm not sure if this is for EF4 only but I got the tip from Entity Framework 4.0 Recipes


var listOfIds=GetAListOfIds();
var context=CreateEntityFrameworkObjectContext();
var results = from item in context.Items
              where listOfIds.Contains(item.Category.Id)
              select item;
//results contains the items with matching category Ids

This query generates the correct in clause on the server side. I haven't tested it with EF 3.5 but it does work with EF4.

NB: The values passed into the in clause are NOT parameters so make sure you validate your inputs.

like image 67
Michael Brown Avatar answered Oct 12 '22 01:10

Michael Brown


It is somewhat of a shame that Contains is not supported in Linq to Entities.

IN and JOIN are not the same operator (Filtering by IN never changes the cardinality of the query).

like image 26
Amy B Avatar answered Oct 12 '22 00:10

Amy B