使用 Identity 2.0 注册用户后,在数据库中创建了用户,Account 控制器中有代码用于创建身份并登录用户。这是我收到错误的时候。这是产生错误的代码:
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
这是错误:
实体类型 IdentityRole 不是当前上下文模型的一部分。
我的模型如下所示:
namespace MyApp.Models
{
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
}
public class ApplicationRole : IdentityRole
{
[Required]
[StringLength(50)]
public string ProperName { get; set; }
[Required]
public string Description { get; set; }
}
public class MyAppDb : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public MyAppDb()
: base("MyAppDb")
{
}
}
}
MyUserManager
在 Account 控制器中是这样创建的:
namespace MyApp.Controllers
{
[Authorize]
public class AccountController : BaseController
{
private UserManager<ApplicationUser> _userManager;
public AccountController()
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager
{
get
{
return _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyAppDb()));
}
private set
{
_userManager = value;
}
}
...
}
}