【发布时间】:2014-02-26 19:21:23
【问题描述】:
IdentityDbContext 导致添加到 AspNetRoles 的属性/字段出现问题
我认为问题出在 IdentityDbContext 采用 IdentityUser 类型:
public class MyIdentityDb : IdentityDbContext<ApplicationUser>
{
public IdentityDb()
: base("IdentityDb")
{
}
}
但让我解释一下……
我们可以通过向继承自 IdentityUser 的 ApplicationUser 类添加属性来向 AspNetUsers 表添加字段,这真是太棒了。示例:
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
}
很自然,我们可以通过向继承自 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();
我们控制器上的 Index 方法:
public ViewResult Index(int? page)
{
return View(new IndexViewModel
{
Users = myIdentityDb.Users.ToList(),
Roles = myIdentityDb.Roles.ToList()
});
}
错误出现在“myIdentityDb.Roles.ToList()”上,显示为“无法隐式转换类型System.Collection.Generic.List<Microsoft.AspNet.Identity.EntityFramework.IdentityRole> to System.Collections.Generic.IList<MyApp.Models.ApplicationRole>...
当然,我们可以将 ViewModel 更改为使用 IdentityRole 类型,如下例所示,但是我们无法访问 AspNetRoles 表中的新“ProperName”字段:
public class IndexViewModel
{
public IList<ApplicationUser> Users { get; set; }
public IList<IdentityRole> Roles { get; set; }
}
所以我们可以尝试创建另一个 Db 类并传递一个 IdentityRole 类型而不是 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();
并更改我们控制器上的 Index 方法:
public ViewResult Index(int? page)
{
return View(new IndexViewModel
{
Users = myIdentityDb.Users.ToList(),
Roles = myIdentityRolesDb.Roles.ToList()
});
}
但我们最终会遇到同样的问题; IdentityDbContext 采用 IdentityUser 类型的事实。
有什么想法可以让我们使用自定义字段/属性获取角色列表吗?
【问题讨论】:
标签: c# asp.net-mvc-5 entity-framework-6 asp.net-identity