Get a list of elements by their ID in entity framework

Shawn Mclean picture Shawn Mclean · Apr 11, 2011 · Viewed 74.4k times · Source

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'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.

Answer

moi_meme picture moi_meme · Apr 11, 2011
var listOfRoleId = user.Roles.Select(r => r.RoleId);
var roles = db.Roles.Where(r => listOfRoleId.Contains(r.RoleId));