0

在 LAMBDA-Expressions 中,如何获取所有用户(姓名和 ID)及其分配的角色(姓名、ID)

我很难弄清楚这个连接的 Lambda 语法!

例如:

UserProfile:
Username, UserId
Ken,      1
Barbie,   2
Alice,    3

webpages_Roles:
RoleName, RoleId
Admin,    1
Editor,   2
Guest,    3

webpages_UsersInRoles
UserId, RoleId
1,      1
1,      2
2,      1

Result should be:
UserName, RoleName, UserId, RoleId
Ken,      Admin,     1,      1
Ken,      Editor,    1,      2
Barbie,   Admin,     2,      1

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<UsersInRole> UsersInRole { get; set; }
}

[Table("webpages_Roles")]
public class Role
{
    public Role()
    {
        Members = new List<Membership>();
    }

    [Key]
    public int RoleId { get; set; }
    [StringLength(256)]
    public string RoleName { get; set; }

    public ICollection<Membership> Members { get; set; }
    public virtual ICollection<UsersInRole> UsersInRole { get; set; }
}


[Table("webpages_UsersInRoles")]
public class UsersInRole
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }
    public virtual UserProfile User { get; set; }

    [Key, Column(Order = 1)]
    public int RoleId { get; set; }
    public virtual Role Role { get; set; }
}
4

3 回答 3

2

如果通过 lambda 语法你的意思是方法链语法,这里是它:

var result = db.UserProfiles.Join(db.webpages_UsersInRoles, u => u.UserId, ur => ur.UserId, (u, ur) => new {u, ur})
            .Join(db.webpages_Roles, t => t.ur.RoleId, r => r.RoleId, (t, r) => new
                {
                    t.u.UserName,
                    r.RoleName,
                    t.u.UserId,
                    r.RoleId
                });
于 2013-06-17T14:34:23.807 回答
1

您可以使用LINQ

var users = (from users in UserProfile
             from userRoles in users.UsersInRole
             from roles in userRoles.Role
             select new 
             {
               UserName = users.UserName
               , UserId = users.UserId
               , RoleName = roles.RoleName
               , RoleId = roles.RoleId
             }).ToList();
于 2013-06-17T14:29:53.313 回答
1

如果您使用的是实体框架,以下代码将返回您想要的内容。

using(var context = new DBContext()){ 
        return context.UserProfiles;
}
于 2013-06-17T14:32:43.867 回答