Get a list of elements by their ID in entity framework

前端 未结 3 1637
花落未央
花落未央 2021-02-05 00:49

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.

<
相关标签:
3条回答
  • 2021-02-05 01:21
    var listOfRoleId = user.Roles.Select(r => r.RoleId);
    var roles = db.Roles.Where(r => listOfRoleId.Contains(r.RoleId));
    
    0 讨论(0)
  • 2021-02-05 01:45

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

    0 讨论(0)
  • 2021-02-05 01:46

    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.

    0 讨论(0)
提交回复
热议问题