Get a list of elements by their ID in entity framework
How can I get all elements that are in another list by ID? I have List roles; I'd like to get all roles from the database that are in this list by their Id.
I'm using code-first.
I did this and it threw an error:
var roles = db.Roles.Where(r => user.Roles.Any(ur => ur.RoleId == r.RoleId));
RoleId
is of type int.
Error:
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));
Something like this should work if user.Roles is a list of ints:
var roles = db.Roles.Where(r => user.Roles.Contains(r.RoleId));
That turns it into a "SELECT WHERE IN (x, y, z...)" in SQL.
You can't combine a local list with remote data, then there is nothing for the db to read from since the data is elsewere (on your client).
I think there might be better solution to what you're trying to do;
It seems like you're trying to fetch all roles assigned to a specific user. If that's the case i would suggest a solution where you're passing the current user id to the database and fetch the roles assigned with a INNER JOIN.
Depending on your database it might look something like this (if you're connecting users with roles through a table called 'UserRoles')
var roles = db.UserRoles.Where(x => x.UserID == <insert id>).Select(x => x.Role)
(Of course you could also create a stored procedure returning a list of 'Role' if you like directly in your db and map it.)
精彩评论