简体   繁体   English

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

[英]lambda expression join multiple tables with select and where clause

I have three table many to many relationship I have joined the three table and select the value I want but now I need to select one row from the query result by where by specifying the id this is my three table我有三个表多对多关系我已经加入了三个表并选择了我想要的值但是现在我需要从查询结果中选择一行通过指定 id 这是我的三个表

And this is the query using LINQ lambda expression :这是使用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());
}

the result will be like that using sql query结果将是使用sql查询的结果

sql query sql查询

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

result of the sql query sql查询的结果

now i use anther sql query to filter the result of previews sql query by where and set the condition to where u.UserId = 1 to only give me back the user with the id 1 like that现在我使用另一个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

and the result of this sql query以及这个sql查询的结果

so how can i add the where clause to my lambda expression to give me the same result as the result of the sql query and thanks for any help那么如何将 where clause添加到我的 lambda 表达式中,以给我与sql查询结果相同的结果,感谢您的帮助

If I understand your questions correctly, all you need to do is add the .Where(m => mruUserId == 1) :如果我正确理解您的问题,您需要做的就是添加.Where(m => mruUserId == 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
    });

Hope that helps.希望有帮助。

I was looking for something and I found this post.我正在寻找一些东西,我发现了这篇文章。 I post this code that managed many-to-many relationships in case someone needs it.我发布了这段管理多对多关系的代码,以防有人需要它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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