1

我有两种实体类型:具有多对多关系的角色和用户。即 Role 具有 Users 属性,而 User 具有 Roles 属性。我必须使用属于已定义角色的用户名获取字符串数组。我写了一些代码,但它并不优雅。我想用一个 linq 表达式来做到这一点。是否可以?

public override string[] GetUsersInRole(string roleName)
{
    List<string> names = new List<string>();
    using (MembershipDb db = new MembershipDb())
    {
        Role role = db.Roles.FirstOrDefault(r => r.Name == roleName);
        foreach (User u in role.Users)
        {
            names.Add(u.UserName);
        }
    }
    return names.ToArray();
}
4

2 回答 2

2

看这个:

public override string[] GetUsersInRole(string roleName)
{
    using (MembershipDb db = new MembershipDb())
    {
        return db.Roles
           .Where(r => r.Name == roleName)
           .SelectMany(r => r.Users, (r, s) => s.User.UserName).ToArray();
    }
}
于 2012-12-28T10:44:14.930 回答
2
return db.Roles.Where(r => r.Name == roleName)
               .SelectMany(r => r.Users)
               .Select(u => u.UserName)
               .ToArray();
于 2012-12-28T10:47:32.470 回答