在Microsoft.AspNet.Identity中使用UserManager和RoleManager;

Jam*_*mes 7 c# entity-framework

我以前用过这个,我不能为我生活中的生活弄明白什么是错的.

@using System.Data.Entity;
@using Microsoft.AspNet.Identity;
@using Microsoft.AspNet.Identity.EntityFramework;


using(ApplicationDbContext db = new ApplicationDbContext())
{
   var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
   var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

   var user = User.Identity.GetUserId();

        if(user != null)
        {
            string role = "Admin";
            if (!rm.RoleExists(role))
            {
                var roleResult = rm.Create(new IdentityRole(role));
                if (!roleResult.Succeeded) { //error stuff
                };
            }
            if (!um.IsInRole(user, role))
            {
                um.AddToRole(user, role);
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我跳过创建一个角色元素(因为我已经将它添加到数据库中),但当它到达'是管理员角色的用户'位时,行um.AddToRole(用户,运行,但后来我收到一个错误,说明我有违规,因为我试图复制密钥.

我不明白为什么调试时的程序说"没有这个名字的用户具有Admin的角色",稍后当它试图添加该角色时,我会看到"嘿,那个用户已经有Admin的角色,你不能再添加它"

在我使用RoleProviders之前,我必须更改我的web.config并将信息添加到那里,但我没有这样做,因为我没有!?

它可能很简单,但我被卡住了.

为了清楚起见,我如何检查当前登录的用户是否属于具有AspNet.Identity的角色"Admin".

亲切的问候

Jam*_*mes 2

好吧,问题证明是关闭延迟加载导致了这个问题。我将 Microsoft Identity 更新到 2.0 但仍然不高兴。显然这是他们正在解决的一个已知错误。

不理想,因为我总是关闭延迟加载。它不是一个大型应用程序,因此性能不是问题。只是为了让所有人都知道。