Layui

Asp.Net Identity 2.0 Custom Role Manager: The entity type IdentityRole is not part of the model for the current context

匿名 (未验证) 提交于 2018-04-10 12:30:22

问题:

I have customized the RoleManager in a WebForms ASP.NET application in order to integrate a new field in the Roles table.

I've followed the instructions given here: http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/

So in the identitymodels.cs I have added:

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }
    public int Level{ get; set; } //this is the new field in the Roles table
}

and modified the OnModelCreating method:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder); // This needs to go before the other rules!

        modelBuilder.Entity().ToTable("Users").Property(p => p.Id).HasColumnName("UserId");
        modelBuilder.Entity().ToTable("UserRoles");
        modelBuilder.Entity().ToTable("UserLogins");
        modelBuilder.Entity().ToTable("UserClaims").Property(p => p.Id).HasColumnName("UserClaimId");
        modelBuilder.Entity().ToTable("Roles").Property(p => p.Id).HasColumnName("RoleId");
        modelBuilder.Ignore();
        modelBuilder.Ignore();
    }

then in the file IdentityConfig.cs I've added:

    public class ApplicationRoleManager : RoleManager
{
    public ApplicationRoleManager(
        IRoleStore roleStore)
        : base(roleStore)
    {
    }
//I'm not really sure about the following (IOwinContext??):
    public static ApplicationRoleManager Create(
        IdentityFactoryOptions options, Microsoft.Owin.IOwinContext context)
    {
        return new ApplicationRoleManager(
            new RoleStore(context.Get()));
    }
}

So now trying to create a new role:

var roleManager = new RoleManager(new RoleStore(new ApplicationDbContext())); 
//the above line differs from what is described in the above blog post.

ApplicationRole existingRole = roleManager.FindByName(newRoleName); //ERROR!!
if(existingRole==null)
    {            
        var role = new ApplicationRole();
        role.Name = newRoleName;
        int grade = 0;
        if(int.TryParse(TxtGrade.Text,out grade))
        {
            role.Level= level;
        }
        roleManager.Create(role);
    }

I get the following error:

The entity type IdentityRole is not part of the model for the current context.

And below the stack:

System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType) +208
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +51
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +137
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +38
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +98
   System.Linq.Queryable.Any(IQueryable`1 source, Expression`1 predicate) +84
   Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`6.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +4106
   System.Data.Entity.DbContext.GetValidationErrors() +290
   System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken) +151
   System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken) +75
   System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken) +60
   System.Data.Entity.DbContext.SaveChangesAsync() +63
   Microsoft.AspNet.Identity.EntityFramework.d__2.MoveNext() +215
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
   Microsoft.AspNet.Identity.CultureAwaiter.GetResult() +63
   Microsoft.AspNet.Identity.d__0.MoveNext() +925
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
   Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +409
   Microsoft.AspNet.Identity.RoleManagerExtensions.Create(RoleManager`2 manager, TRole role) +245

on the method roleManager.Create(role);

Please note that roleManager is not null, and the whole identity authentication is working fine.

It seems like I've missed some changes on the IdentityRole and it's still called by the create method.

How can I solve this error? I've missed to change something?