实体框架——使用lambda表达式编写查询

时间:2022-12-19 09:51:32

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

我刚刚启动了Entity Framework & linq并编写了这个查询

 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.

上面的代码可以很好地满足我的需要,但是我也在尝试使用lambda表达式来编写这个代码。

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 个解决方案

#1


2  

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

#2


1  

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.

我要跳到前面假设你已经定义了多对多关系中的RolePermission和RoleUser之间的关系?这会让你的生活更简单。

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.

当然,这取决于你如何建立人际关系。

#1


2  

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

#2


1  

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.

我要跳到前面假设你已经定义了多对多关系中的RolePermission和RoleUser之间的关系?这会让你的生活更简单。

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.

当然,这取决于你如何建立人际关系。

相关文章