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

喜欢而已 提交于 2019-12-08 15:53:25

问题


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.


回答1:


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));



回答2:


Your problem is you can't intersect users on long ids. Intersect can only be used on IEnumerables of the same type.

You should use user.Id.GetValueOrDefault() because your ID is long? instead of long.



来源:https://stackoverflow.com/questions/7011033/getting-entities-whose-keys-match-listor-array-of-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!