获取其键匹配ID列表(或数组)的实体 [英] Getting Entities whose keys match list(or array) of ids
问题描述
我正在使用CodeFirst EntityFramework.我有一个使用context.Users返回的IQueryable<User>
实体;其中context是EntityFramework的DbContext.从此列表中,我必须选择ID包含在一组ID(长整数)中的ID. ID是用户实体的主键.我尝试了以下操作,但出现编译器错误.
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
编译错误是(找不到相交/包含的定义) 注意:System.Linq已经导入.
Compilation error is (no definition found for Intersect/Contains) Note: System.Linq is already imported.
推荐答案
确保您引用的是System.Linq
Make sure you are referencing System.Linq
例如using System.Linq
然后,user.Id必须为long类型.您在评论中说过很长?因为您认为那是您需要使用主键的方式.解决方案是使用很长的时间,并利用实体框架的自动生成id选项.
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.
对于可能为null的非主键,更常见的情况是将contains选项与value或default运算符配合使用.
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));
这篇关于获取其键匹配ID列表(或数组)的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!