Entity Framework - attribute IN Clause usage

unairoldan picture unairoldan · Nov 12, 2012 · Viewed 53.2k times · Source

I need to filter some Entities by various fields using "normal" WHERE and IN clauses in a query over my database, but I do not know how to do that with EF.

This is the approach:

Database table

Licenses
-------------
license INT
number INT
name VARCHAR
...

desired SQL Query in EF

SELECT * FROM Licenses WHERE license = 1 AND number IN (1,2,3,45,99)

EF Code

using (DatabaseEntities db = new DatabaseEntities ())
{
    return db.Licenses.Where(
        i => i.license == mylicense 
           // another filter          
        ).ToList();
}

I have tried with ANY and CONTAINS, but I do not know how to do that with EF.

How to do this query in EF?

Answer

Albin Sunnanbo picture Albin Sunnanbo · Nov 12, 2012
int[] ids = new int[]{1,2,3,45,99};
using (DatabaseEntities db = new DatabaseEntities ())
{
    return db.Licenses.Where(
        i => i.license == mylicense 
           && ids.Contains(i.number)
        ).ToList();
}

should work