Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 647
Shawn Mclean Avatar asked Apr 11 '11 16:04

Shawn Mclean


People also ask

How do I get identity value in EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

How do I use Find in Entity Framework?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.


2 Answers

var listOfRoleId = user.Roles.Select(r => r.RoleId); var roles = db.Roles.Where(r => listOfRoleId.Contains(r.RoleId)); 
like image 165
moi_meme Avatar answered Sep 21 '22 19:09

moi_meme


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.

like image 44
Chris Smith Avatar answered Sep 21 '22 19:09

Chris Smith