如何将此Linq查询语法转换为方法语法?

4

这里的答案包含以下查询语句:

var query = from role in _db.Roles
            where role.Name == roleName
            from userRoles in role.Users
            join user in _db.Users
            on userRoles.UserId equals user.Id
            select user;

我该如何使用Linq方法语法重现相同的查询?

1
步骤1:使用resharper。我认为它可以为您复现它。 - M.kazem Akhgary
LinqPad可以为您完成这项任务。 - Alexander Petrov
2个回答

3
var query = _db.Roles
    .Where(role => role.Name == roleName)
    .SelectMany(role => role.Users)
    .Join(_db.Users, userRole => userRole.UserId, user => user.Id, (role, user) => user);

一些解释

var query = from role in _db.Roles
        where role.Name == roleName // this will be translated to .Where
        from userRoles in role.Users // this is .SelectMany
        join user in _db.Users // this is .Join
        on userRoles.UserId equals user.Id // second and third arguments of .Join
        select user; // last argument of .Join

我有什么遗漏吗?那是查询的字面意思,但第三行有什么意义呢?编辑:角色是否真的有一个名为“用户”的导航属性,而不是由用户组成的吗? - ChrisV
根据最初的查询(参见“on userRoles.UserId equals user.Id”部分),我理解Role具有UserRole {UserId,RoleId}对象的集合。 - hazzik
@ChrisV 另外,这不是逐字翻译。逐字翻译在 Ricky 的回答中。 - hazzik
@ChrisV 的原始问题与 AspNet Identity 有关。请查看以下来源:https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNet.Identity.EntityFramework/IdentityRole.cs#L52 和 https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNet.Identity.EntityFramework/IdentityUserRole.cs。 - hazzik

0

这是方法语法版本

    var query =
        _db.Roles.Where(role => role.Name == roleName)
            .SelectMany(role => role.Users, (role, userRoles) => new {role, userRoles})
            .Join(_db.Users, @t => userRoles.UserId, user => user.Id, (@t, user) => user);

在 SelectMany 中,你不需要使用匿名类型的 resultSelector,因为你只使用其中的 userRoles。 - hazzik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接