Get a list of elements by their ID in entity framework

Solution 1:

var listOfRoleId = user.Roles.Select(r => r.RoleId);
var roles = db.Roles.Where(r => listOfRoleId.Contains(r.RoleId));

Solution 2:

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.

Solution 3:

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