我有两个实体类型:Role和User,它们具有多对多关系。即角色具有Users属性,而用户具有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();
}
return db.Roles.Where(r => r.Name == roleName)
.SelectMany(r => r.Users)
.Select(u => u.UserName)
.ToArray();
看这个:
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();
}
}