简体   繁体   中英

Entity Framework - writing query using lambda expression

I have just started Entity Framework & linq and write this query

 var query = from rp in db.UM_RolePermission
             where (from ru in db.UM_RoleUser 
             where ru.UM_User.UserID == userId select ru.RoleID).Contains(rp.RoleId)
             select rp;

above is working fine and fullfill my need, however I am trying to write this same using lambda expression to understand that as well.

I have tried himself to write this but I was unable to complete it.

var query1 = db.UM_RolePermission
             .Where(rp => (from ru in db.UM_RoleUser where ru.UM_User.UserID == userId select ru.RoleID).Contains(rp.RoleId));

Can anyone complete this?

RelationShip:

UM_RoleUser and UM_User

Thanks

var query = db.UM_RolePermission
            .Where(rp => db.UM_RoleUser
                         .Where(ru => ru.UM_User.UserID == userId)
                         .Select(ru => ru.RoleID)
                         .Contains(rp.RoleId))

I going to jump ahead and assume you've defined a relationship between RolePermission and RoleUser in a many-to-many relationship? That will make your life a lot simpler.

var query1 = db.UM_RoleUser
    .Where(ru => ru.UserId == userID)
    .SelectMany(rp => rp.RolePermissions);

Of course, this depends on how you've set up your relationships.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM