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

时间:2015-06-29 23:28:53

标签: c# .net linq entity-framework

answer here包含以下查询:

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方法语法重现相同的查询?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);