获取其键匹配id列表(或数组)的实体

Jat*_*tin 10 linq linq-to-entities entity-framework-4.1

我正在使用CodeFirst EntityFramework.我有一个IQueryable<User>使用context.Users返回的实体; 其中context是EntityFramework的DbContext.从这个列表中我必须选择Id包含在Ids(long)数组中的那些.Id是用户实体的主键.我尝试了以下但得到编译器错误.

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
Run Code Online (Sandbox Code Playgroud)

编译错误是(没有找到Intersect/Contains的定义)注意:System.Linq已经导入.

Bob*_*ale 15

确保您引用System.Linq

例如 using System.Linq

然后user.Id必须是long类型.你在评论中说过它很长?因为你相信你需要使用主键.解决方案是使用long并使用实体框架的autogenerate id选项.

或者,对于可能为null的非主键,更常见的情况是将contains选项与value或default运算符一起使用.

users.Where(user=>ids.Contains(user.id??0));
Run Code Online (Sandbox Code Playgroud)