【问题标题】:ApplicationUser and ApplicationRole navigation properties in Identity 2.0.0Identity 2.0.0 中的 ApplicationUser 和 ApplicationRole 导航属性
【发布时间】:2014-09-09 11:29:37
【问题描述】:

在 Identity 2.0.0 中,我们在 ApplicationUser 中有 Roles 导航属性,类型为 IdentityUserRoles 我们在 IdentityRole 中具有相同类型的 IdentityUserRoles 的用户导航属性

在这里

namespace Microsoft.AspNet.Identity.EntityFramework
{
    // Summary:
    //     EntityType that represents a user belonging to a role
    //
    // Type parameters:
    //   TKey:
    public class IdentityUserRole<TKey>
    {
        public IdentityUserRole();

        // Summary:
        //     RoleId for the role
        public virtual TKey RoleId { get; set; }
        //
        // Summary:
        //     UserId for the user that is in the role
        public virtual TKey UserId { get; set; }
    }
}

所以,当我遍历 context.Users 时,我只能得到 RoleId

有没有办法在 ApplicationUser 和 ApplicationRole 之间建立标准的多对多映射?

我希望能够做这样的事情

foreach (var user in ApplicationDbContextInstance.Users)
{
    List<ApplicationRole> UserRoles = user.Roles.ToList();
    /*
    some logic ... 
    */ 
}

更新:

在解决这个问题后,我找到了适合我的情况的解决方案。 也许它没有那么优雅,但在我的情况下,我必须使用额外的导航属性扩展 IdentityUserRole

我已将 IdentityUserRole 扩展到 ApplicationUserRole 并在所有解决方案中进行适当的更改。 这是我的新 IdentityUserRole:

public class ApplicationUserRole : IdentityUserRole<string>
{
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
    public virtual ICollection<GeoSectorForUser> GeoSectors { get; set; }
}

现在我可以像这样让所有用户担任特定角色:

foreach(ApplicationRole role in db.Roles){
    List<ApplicationUser> users = role.Users.Select(s => s.User).ToList();
}

在我的情况下,需要 AplicationUserRole 来存储其他导航属性,以便解决方案适合我。 但我仍然想知道如何在 IdentityUser 和 IdentityRole 之间创建干净的多对多关系

【问题讨论】:

  • IdentityUserRole 是已经提供多对多关系的中间对象。所以IdentityUser IdentityUserRole `IdentityRole'
  • 您的更新对我不起作用。尝试创建新迁移时出现异常。

标签: c# asp.net-identity-2


【解决方案1】:

IdentityUser.Roles() 为您提供一组 IdentityUserRole 对象,其中仅包含 RoleIdUserId 属性。要为用户获取 Role 对象的集合,您应该使用 RoleManager 类(在我的脑海中输入这个,所以可能无法 100% 工作):

var roleManager = new RoleManager();

foreach (var user in ApplicationDbContextInstance.Users)
{
    List<IdentityUserRole> UserRoles = user.Roles.ToList();

    foreach(var userRole in UserRoles)
    {
        var role = roleManager.FindbyId(userRole.RoleId);
    }

}

【讨论】:

  • 是的。这就是我必须使用它的方式。但我的问题是关于标准多对多映射的可能性。无论如何,谢谢你的回答
猜你喜欢
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多