5

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

2 Answers 2

4
var query = db.UM_RolePermission
            .Where(rp => db.UM_RoleUser
                         .Where(ru => ru.UM_User.UserID == userId)
                         .Select(ru => ru.RoleID)
                         .Contains(rp.RoleId))
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

There is no relationship b/w RolePermission & RoleUser
Why not make one? It certainly sounds like a natural relationship to me based on what you've told me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.