Extending ASP.NET Identity Roles: IdentityRole is not part of the model for the current context

后端 未结 6 1498
鱼传尺愫
鱼传尺愫 2020-12-15 08:37

I\'m trying to use the new ASP.NET Identity in my MVC5 application, specifically I\'m trying to integrate ASP.NET Identity into an existing database. I\'ve already read the

6条回答
  •  醉梦人生
    2020-12-15 08:55

    I know this is an old question, but just in case someone else is having a hard time adding roles/users when they modified asp identity to use numeric primary keys (int/long) instead of the default string for the Identity Roles, so if you have changed the IdentityUserRole in IdentityModels.cs to something like this:

    public class Role : IdentityRole
    {
        public Role() { }
        public Role(string name) { Name = name; }
    }
    

    You have to use the class Role instead of the default IdentityRole when constructing the RoleManager, so your code should be like this:

    public static void RegisterUserRoles()
    {
         ApplicationDbContext context = new ApplicationDbContext();
    
         var RoleManager = new RoleManager(new RoleStore(context));
    
         if (!RoleManager.RoleExists("Administrador"))
         {
             var adminRole = new Role {
                  Name = "Administrador",
             };
             RoleManager.Create(adminRole);
         }
    }
    

    So this should populate your database properly, I think all experienced ASP programmers already know this, but for others this could take some time to figure out.

提交回复
热议问题