我使用Identity2.0與MVC5CodeFirst我已經延長兩個IdentityUser
和IdentityRole
這樣的:從IdentityDbContext
爲什麼UserManager.CreateIdentityAsync()正在尋找IdentityRole以及如何解決?
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")
{
}
}
注意MyAppDb
繼承,但我通過的ApplicationRole
代替IdentityRole
。我的ApplicationRole
繼承自IdentityRole
,所以這應該不成問題。在此代碼
The entity type IdentityRole is not part of the model for the current context.
在UserManager.CreateIdentityAsync(...)
:
但是...
我AccountController
引發此錯誤
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
的user
正在這裏創造:
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
什麼是「主要故障」? ;)
UPDATE: 我相當肯定的問題有事情做與UserStore
這裏:
public class AccountController : Controller
{
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyAppDb())))
{
}
public AccountController (UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
UserManager.PasswordValidator = (IIdentityValidator<string>)new MinimumLengthValidator(8);
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
}
public UserManager<ApplicationUser> UserManager { get; private set; }
...
如何獲得UserStore
瞭解ApplicationRole
的時候,我只能將它傳遞一個論據?
這可能是有益的注意,該項目的啓動與AspNetIdentity1 *,然後升級到AspNetIdentity2.0。升級後,我擴展了IdentityRole,更改了MyAppDb的簽名,正如您在上面的問題中所看到的,問題開始了。 –
您的'user'是否有任何與其關聯的'Roles'。如果是,請說明'用戶'是如何創建的。 – haim770
是的。我創建了這樣的用戶: var result = await UserManager.CreateAsync(user,model.Password); 其中「用戶」是ApplicationUser。我直接在數據庫中將用戶添加到角色,從Users表中複製UserId,並從Roles表中複製RoleId。非常直截了當。 –