找不到实体类型IdentityRole

时间:2015-04-18 06:28:50

标签: c# entity-framework asp.net-identity

我正在使用AspNet Identity 3.0.0.beta3和现有数据库。我的配置非常简单。

当我尝试登录时,我不断收到此错误

ModelItemNotFoundException:实体类型' IdentityRole'没找到。确保已将实体类型添加到模型中。

有人可以帮我解决这个问题。

这是我的代码:

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int PrimaryAccountId { get; set; }
}

public class Role : IdentityRole { }

public class UserRole : IdentityUserRole { }

public class RoleClaim : IdentityRoleClaim { }

public class UserClaim : IdentityUserClaim { }

public class UserLoginsExternal : IdentityUserLogin<string> { }


public class HOPContext : IdentityDbContext<User, Role, string>
{

    private string connectionString;

    public HOPContext(string connString)
    {
        this.connectionString = connString;
    }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseSqlServer(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        //base.OnModelCreating(builder);

        builder.Entity<User>(b =>
        {
            b.Key(u => u.Id);
            b.ForRelational().Table("User");
            b.Property(u => u.ConcurrencyStamp).ConcurrencyToken();
        });

        builder.Entity<Role>(b =>
        {
            b.Key(r => r.Id);
            b.ForRelational().Table("Role");
            b.Property(r => r.ConcurrencyStamp).ConcurrencyToken();
        });

        builder.Entity<UserClaim>(b =>
        {
            b.Key(uc => uc.Id);
            b.HasOne<User>().WithMany().ForeignKey(uc => uc.UserId);
            b.ForRelational().Table("UserClaim");
        });

        builder.Entity<RoleClaim>(b =>
        {
            b.Key(rc => rc.Id);
            b.HasOne<Role>().WithMany().ForeignKey(rc => rc.RoleId);
            b.ForRelational().Table("RoleClaim");
        });

        builder.Entity<UserRole>(b =>
        {
            b.Key(r => new { r.UserId, r.RoleId });
            b.ForRelational().Table("UserRole");
        });

        builder.Entity<UserLoginsExternal>(b =>
        {
            b.Key(l => new { l.LoginProvider, l.ProviderKey });
            b.HasOne<User>().WithMany().ForeignKey(uc => uc.UserId);
            b.ForRelational().Table("UserLoginsExternal");
        });
    }
}

1 个答案:

答案 0 :(得分:0)

在`Startup.cs中检查你的配置,见下文:

 public void ConfigureServices(IServiceCollection services)
  {
...

 services.AddIdentity<User , Role >() .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
...
}

确保将您的IdentityUserIdentityRole继承的课程传递给services.AddIdentity<TUser,TRole>()