C# 用户角色未保存在ASP.NET标识中

C# 用户角色未保存在ASP.NET标识中,c#,asp.net-mvc,asp.net-identity,C#,Asp.net Mvc,Asp.net Identity,我正在使用EntityFramework6运行MVC5,并使用ASP.NET身份验证。出于某种我无法理解的原因,我似乎无法将用户分配到角色并使其保持不变。考虑下面的代码: List<string> roles_1, roles_2; using (ApplicationDbContext context = new ApplicationDbContext()) { UserManager<ApplicationUser> userManager = new Us

我正在使用EntityFramework6运行MVC5,并使用ASP.NET身份验证。出于某种我无法理解的原因,我似乎无法将用户分配到角色并使其保持不变。考虑下面的代码:

List<string> roles_1, roles_2;
using (ApplicationDbContext context = new ApplicationDbContext())
{
    UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    userManager.AddToRole(User.Identity.GetUserId(), "Webmaster");
    context.SaveChanges();
    roles_1 = userManager.GetRoles(User.Identity.GetUserId()).ToList();
}
using (ApplicationDbContext context = new ApplicationDbContext())
{
    UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    roles_2 = userManager.GetRoles(User.Identity.GetUserId()).ToList();
}
列出角色1、角色2;
使用(ApplicationDbContext context=new ApplicationDbContext())
{
UserManager UserManager=newusermanager(newuserstore(context));
userManager.AddToRole(User.Identity.GetUserId(),“网站管理员”);
SaveChanges();
roles_1=userManager.GetRoles(User.Identity.GetUserId()).ToList();
}
使用(ApplicationDbContext context=new ApplicationDbContext())
{
UserManager UserManager=newusermanager(newuserstore(context));
roles_2=userManager.GetRoles(User.Identity.GetUserId()).ToList();
}

运行此代码后,“roles_1”中有一个项目(“Webmaster”),而“roles_2”为空。不知何故,角色分配没有在上下文之间保存。当我直接查看AspNetUserRoles表时,有一行包含该用户和角色之间的链接。因此,它正确地保存了它,但是新上下文没有正确地加载它。有什么想法可以解释为什么会这样吗?

为什么不使用UserManager类而直接使用上下文?我使用的是“AppUserManager”类,它只是扩展了UserManager,但带有一个自定义的UserValidator。我对代码进行了编辑,使其更有意义。如您所见,它确实创建了UserManager类,并使用该类添加角色。