【发布时间】:2015-05-19 15:57:55
【问题描述】:
我在为我的数据库添加用户和角色时遇到问题。
用户和角色都被创建了(我可以在抛出错误后在数据库中看到它们)。
但是,当我尝试检查用户是否在某个角色中时,我得到了一个异常。
我的代码是:
public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext>
{
protected override void Seed(tbContext context)
{
ApplicationDbContext userscontext = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(userscontext);
var userManager = new UserManager<ApplicationUser>(userStore);
var roleStore = new RoleStore<IdentityRole>(userscontext);
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
{
var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" };
userManager.Create(user, "Pa$$W0rD!");
}
if (!roleManager.RoleExists("Admin"))
{
roleManager.Create(new IdentityRole("Admin"));
}
if(!userManager.IsInRole("marktest","Admin"))
{
userManager.AddToRole("marktest","Admin");
}
不过,就行了:
if(!userManager.IsInRole("marktest","Admin"))
抛出异常并报错:UserId not found.
当我在抛出异常后检查时,用户和角色都在数据库中:
谁能看出我做错了什么?
感谢您的帮助,
标记
【问题讨论】:
-
你在
if(!userManager.IsInRole("marktest","Admin"))之前试过SaveChanges()吗? -
嗨 - 是的,我在该行之前添加了
context.SaveChanges();,但仍然会引发具有相同错误的异常。谢谢,马克 -
那么“marktest”用户是否保存在数据库中?
-
嗨 - 是的,我已在问题中添加了屏幕截图。再次感谢,马克
标签: c# asp.net-mvc asp.net-mvc-4 asp.net-identity