c# - Identity 2.0.0 中的 ApplicationUser 和 ApplicationRole 导航属性

标签 c# asp.net-identity-2

在 Identity 2.0.0 中,我们在 ApplicationUser 中有 Roles 导航属性,类型为 IdentityUserRoles 并且我们在 IdentityRole 中有相同类型 IdentityUserRoles 的 Users 导航属性

在这里

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 之间创建干净的多对多关系

最佳答案

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);
    }

}

关于c# - Identity 2.0.0 中的 ApplicationUser 和 ApplicationRole 导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823092/

相关文章:

c# - 静态变量是否是线程安全的,因为您可以从多个线程读取/写入而不会崩溃?

c# - ASP MVC 构建对应用程序用户角色导航属性抛出警告?

asp.net - 更改 ASP.NET SPA 模板中的 ASP.NET 标识代码的原因?

c# - 启用 SSL 网站时阻止加载混合事件内容 "http://connect.facebook.net/en_US/all.js"

c# - 如何恢复已被替换的 HTML 括号?

c# - AuthenticationManager.GetExternalLoginInfoAsync() 始终为空

asp.net-mvc - ASP.NET MVC 5 : Endless redirect to the login page using the site template

asp.net-identity-2 - asp.net mvc identity 2 运行不同项目的两个实例

c# - 0xC0000005 : Access violation reading location 0xffffffffffffffff

c# - 如何使用反射将对象添加到类实例的通用列表属性中