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.
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();
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With