identitydbcontext导致添加到aspnetroles

的属性/字段的问题

我相信问题在这里使用IdentityDBContext拍摄IdentityUser类型:

public class MyIdentityDb : IdentityDbContext<ApplicationUser>
{
    public IdentityDb()
        : base("IdentityDb")
    {
    }
}
.

但让我解释...

很好,我们可以通过向ideryityuser继承的应用程序类添加属性来为aspnetusers表添加字段。示例:

public class ApplicationUser : IdentityUser
    {
        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(50)]
        public string LastName { get; set; }
    }
.

SO自然,我们可以通过将属性添加到从IdentityRole继承的ApplicationRole类中添加字段来为aspnetroles表添加字段。示例:

public class ApplicationRole : IdentityRole
{
    [Required]
    [StringLength(50)]
    public string ProperName { get; set; }
}
.

工作完美。我们可以在数据库中看到字段。我们可以向其添加数据。示例:

RoleManager<ApplicationRole> roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(new MyIdentityDb()));

var role = new ApplicationRole() { Name = name, ProperName = propername };
var result = await roleManager.CreateAsync(role);
.

但现在我们在尝试到达数据时遇到问题。示例:

我们的视图:

public class IndexViewModel
{
    public IList<ApplicationUser> Users { get; set; }
    public IList<ApplicationRole> Roles { get; set; }
}
.

在我们的控制器上:

private MyIdentityDb myIdentityDb = new MyIdentityDb();
.

我们的控制器上的索引方法:

public ViewResult Index(int? page)
{
     return View(new IndexViewModel
     {
          Users = myIdentityDb.Users.ToList(),
          Roles = myIdentityDb.Roles.ToList()
     });
}
.

错误位于“myidentitydb.rooles.tolist()”和读取“无法隐式转换类型生成类型...

当然,我们可以更改我们的视图以使用类型的IdentityRole,如以下示例,但是我们无法进入aspnetroles表中的新“precername”字段:

public class IndexViewModel
{
    public IList<ApplicationUser> Users { get; set; }
    public IList<IdentityRole> Roles { get; set; }
}
. 所以我们可以尝试创建另一个DB类并将其传递idityRole类型而不是IdentityUser:

public class MyIdentityDb : IdentityDbContext<ApplicationUser>
{
    public MyIdentityDb()
        : base("MyIdentityDb")
    {
    }
}

public class MyIdentityRolesDb : IdentityDbContext<ApplicationRole>
{
    public MyIdentityRolesDb()
        : base("MyIdentityDb")
    {
    }
}
.

并更改我们的控制器:

private MyIdentityDb myIdentityDb = new MyIdentityDb();
private MyIdentityRolesDb myIdentityRolesDb = new MyIdentityRolesDb();
.

并在我们的控制器上更改我们的索引方法:

public ViewResult Index(int? page)
{
     return View(new IndexViewModel
     {
          Users = myIdentityDb.Users.ToList(),
          Roles = myIdentityRolesDb.Roles.ToList()
     });
}
.

但我们最终得到了同样的问题; IdentityDBContext采用Identityuser类型的事实。

任何想法我们如何获得自定义字段/属性的角色列表?

有帮助吗?

解决方案

因此,如果您升级到2.0.0 beta软件包,则可以直接从角色管理器获取IQueryable:

roleManager.Roles
.

所以您不必下拉到DB上下文,这是1.0中的限制,它已在2.0版本中修复。

其他提示

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top