lambda表达式使用select和where子句连接多个表

时间:2014-04-07 08:57:37

标签: c# asp.net-mvc linq entity-framework join

我有三个表多对多关系我加入了三个表并选择了我想要的值但现在我需要从查询结果中选择一行,通过指定id这是我的三个表{{0} }

这是使用LINQ lambda表达式的查询:

DataBaseContext db = new DataBaseContext();

public ActionResult Index()
{

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Select(m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

    return View(UserInRole.ToList());
}

结果将类似于使用sql查询

sql查询

select * 
from UserProfile u join webpages_UsersInRoles uir on u.UserId = uir.UserId 
                   join webpages_Roles r on uir.RoleId = r.RoleId 

sql查询的结果

现在我使用anther sql查询来过滤预览sql查询的结果,并将条件设置为where u.UserId = 1,只返回ID为1的用户

select * 
from UserProfile u join webpages_UsersInRoles uir on u.UserId = uir.UserId 
                   join webpages_Roles r on uir.RoleId = r.RoleId 
where u.UserId = 1

以及此sql查询的结果

那么如何将clause添加到我的lambda表达式中,以便给出与sql查询结果相同的结果,并感谢您的帮助

2 个答案:

答案 0 :(得分:28)

如果我理解你的问题,你需要做的就是添加.Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

希望有所帮助。

答案 1 :(得分:1)

我正在找东西,我找到了这篇文章。我发布了这个管理多对多关系的代码,以防有人需要它。

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });