通过实体框架中的元素ID获取元素列表 [英] Get a list of elements by their ID in entity framework
本文介绍了通过实体框架中的元素ID获取元素列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何通过ID获取另一个列表中的所有元素?例如我具有列表角色;我想通过ID从此列表中的数据库中获取所有角色.
How can I get all elements that are in another list by ID? For eg; I have List roles; I'd like to get all roles from the database that are in this this list by their Id.
我使用代码优先.
我这样做了,它引发了一个错误:
I did this and it threw an error:
var roles = db.Roles.Where(r => user.Roles.Any(ur => ur.RoleId == r.RoleId));
RoleId
的类型为int.
错误:
无法创建类型为'SampleMVC.Domain.Role'的常量值.在这种情况下,仅支持基本类型(例如Int32,String和Guid).
Unable to create a constant value of type 'SampleMVC.Domain.Role'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
推荐答案
var listOfRoleId = user.Roles.Select(r => r.RoleId);
var roles = db.Roles.Where(r => listOfRoleId.Contains(r.RoleId));
这篇关于通过实体框架中的元素ID获取元素列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文