我正在尝试为我的数据库设定一个初始用户和用户角色,但在这样做时遇到了问题。在查看了so上的类似帖子后,我在种子方法中得到了以下结果:
if (!context.Users.Any(u => u.UserName == "founder"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser {UserName = "founder"};
manager.Create(user, "ChangeItAsap!");
manager.AddToRole(user.Id, "AppAdmin");
}
和我的ApplicationUser类:
public class ApplicationUser : IdentityUser<int, CustomUserLogin,CustomUserRole,CustomUserClaim>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
我的问题是,我在ApplicationUser
上遇到编译错误,说
RecipeManager.Models.ApplicationUser类型不能用作泛型类型或方法
'UserManager<TUser>'
中的类型参数"TUser"。没有从RecipeManager.Models.ApplicationUser
到Microsoft.AspNet.Identity.IUser<string>
的隐式引用转换
ApplicationUser
必须实现IUser<string>
接口。这是用户管理器中允许的类型。问题很可能与密钥的string
数据类型有关。默认的脚手架过程假定string
是更通用的数据类型。您需要将ApplicationUser
类中键的类型更改为字符串,或者继承IUser<int>
或UserManager
中使用的任何类型。