简体   繁体   English

如何将SQL运算符转换为LINQ“ IN”联接

[英]How to convert SQL operator to LINQ “IN” Join

I have this SQL statement: 我有以下SQL语句:

Select Id from dbo.AspNetUsers users Join AspNetUserRoles roles On roles.RoleId in ('2', '4', '5')

which I would like to convert to Linq. 我想转换为Linq。

The closest I could get to it was: 我能找到的最接近的是:

from users in db.AspNetUsers
join roles in db.AspNetUserRoles on new { RoleId = "2" } equals new { RoleId = roles.RoleId }
select new users.Id

which only joins on RoleId = "2" , but I need it to join on RoleId = "4" and "5" as well. 它仅在RoleId = "2"上加入,但我也需要在RoleId = "4" and "5"上加入。 Apparently the "in" keyword is not supported within a join statement in LINQ. 显然,LINQ中的join语句不支持“ in”关键字。

Is there a way to achieve equivalent behaviour in LINQ, possibly using different function syntax? 是否有可能使用不同的函数语法在LINQ中实现等效行为?

Rather than using a JOIN, use a WHERE on the navigation property. 而不是使用JOIN,而是在导航属性上使用WHERE。

I'll leave comments inline as it should be easier to understand. 我将在行内保留评论,因为它应该更容易理解。

string[] roles = new[] { "2", "4", "5" };
var users = db.AspNetUsers
    // for each user
    .Where(user => user.Roles // get the roles
        // select the role id
        .Select(role => role.RoleId)
        // and filter by the wanted roles
        .Where(role => roles.Contains(role))
        // by ensuring any role with one of the wanted IDs exist
        .Any())
    // and then get the IDs of those users
    .Select(user => user.UserId)
    // to finally execute the query
    .ToList();

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

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