【问题标题】:Asp.Net Identity 2.0 Return Roles (By NAME) with a LIST of Users带有用户列表的 Asp.Net Identity 2.0 返回角色(按名称)
【发布时间】:2016-08-03 13:57:52
【问题描述】:

我担心我一定遗漏了一些简单的东西,但是当我执行时:

var results = UserManager.Users.Where(u => u.mgr == appUser.org || appUser.org == "corp");

我得到了符合我要求的 IQueryable ApplicationUser 集合... 除了...集合中的每个 ApplicationUser 都有一个 Roles 属性(集合),它只包括 UserId 和 RoleId 而不是角色的名称。我相信在这个 linq 查询中添加一个 .Include("???") 应该允许我将角色的名称带回每个用户......但我找不到正确的表达式来到达那里。

如何检索分配给集合中每个用户的角色名称?

【问题讨论】:

  • 如果您想使用.Include(),请尝试以下方法之一。您可以将 .Include(x => x.Roles) 用作 lambda 表达式 - 您将需要 using System.Data.Entity。或者,您可以执行 .Include(nameof(ApplicationUser.Roles)) (如果使用 C# 6.0 - 其中 ApplicationUser.Roles 是要包含的 Roles 的类和属性)。两者都会Include 相同的属性。从表面上看,我猜您在上下文中使用带有Users 的EF 作为DbSet<T> 属性,对吧?您的 Roles 属性是导航属性吗?

标签: c# linq asp.net-identity


【解决方案1】:

ASP.NET Identity 中,ApplicationUserRoles 属性是 ApplicationUserRole。该表是ApplicationUsersApplicationRoles 之间的多对多 关系。如果您想获得其他详细信息,则必须使用Include,如您所说:

var results = UserManager
    .Users
    .Where(u => u.mgr == appUser.org || appUser.org == "corp")
    .Include(m => m.Roles.Select(r => r.Role));

正如@GeoffJames 所说,您必须将using System.Data.Entity; 添加到您的使用列表中。

更新

通常您的自定义身份模型应如下所示:

public class ApplicationUserRole : IdentityUserRole
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

ApplicationRole 应该继承 IdentityRole<string, ApplicationUserRole>

public class ApplicationRole 
: IdentityRole<string, ApplicationUserRole>
{
}

ApplicationUser 应该继承IdentityUser&lt;string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim&gt;

public class ApplicationUser 
    : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    .............
}

你也可以看看我的回答here,可能会有帮助。

【讨论】:

  • 请注意,您需要使用 System.Data.Entity 来创建 Include(m =&gt; m...) lambda 表达式
  • in (.Select(r=&gt;r.Role)) "Role" 无法解析,但 RoleId 可以。这让我确切地开始了。 “角色”关系仅将我带到 AspNetUserRoles 表,而不会让我进入角色名称所在的 AspNetRoles 表。
  • @CosCallis,您能否更新您的答案并发布您的模型?因为,通常应该有从 IdentityUserRole 到 IdentityRole 的 Navigation 属性
  • @AdilMammadov,我正在使用 Asp.Net Identity 2.0 提供的 ApplicationUser:IdentityUser 模型我同意“应该是”一个导航属性,但我找不到它......这本质上是个问题。
  • @CosCallis 但接下来的问题应该是如何配置身份模型。请查看我的更新以获取更多信息。
猜你喜欢
  • 2014-12-25
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多