Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Entities whose keys match list(or array) of ids

I am using CodeFirst EntityFramework. I have a IQueryable<User> Entities that are returned using context.Users; where context is DbContext of EntityFramework. From this list I have to choose those whose Id is contained in an array of Ids (long). Id is primary key of User entity. I have tried the following but getting compiler error.

IQueryable<User> users = GetQueryableUsers(); 
long [] ids = GetSelectedIds(); //array of long representing Ids key of User entities
users.Intersect(ids); // compilation error
users.Where(user => ids.Contains(user.Id)); //compilation error

Compilation error is (no definition found for Intersect/Contains) Note: System.Linq is already imported.

like image 739
Jatin Avatar asked Aug 10 '11 12:08

Jatin


1 Answers

Make sure you are referencing System.Linq

e.g. using System.Linq

Then user.Id must be of type long. You've stated in comments that it is long? because you believed that is how you needed to use the primary key. The solution is to use long and make use of the autogenerate id options of the entity framework.

Alternatively a more general case for non primary keys that could be null would be to use the contains option with the value or default operator.

users.Where(user=>ids.Contains(user.id??0));
like image 143
Bob Vale Avatar answered Oct 26 '22 10:10

Bob Vale