InvalidOperationException:无法为 'Role' 创建 DbSet,因为此类型未包含在上下文的模型中

InvalidOperationException: Cannot create a DbSet for 'Role' because this type is not included in the model for the context

以下解决方案适用于 .net core 1.1,但从 1.1 升级到 2.0 后,我收到以下错误:

InvalidOperationException: Cannot create a DbSet for 'Role' because this type is not included in the model for the context.

当用户尝试登录并执行以下语句时:

var result = await _signInManager.PasswordSignInAsync(model.Email, 
                                model.Password, model.RememberMe, lockoutOnFailure: false);

怎么了?


User.cs

public partial class User : IdentityUser<Guid>
{
    public string Name { get; set; }
}

IdentityEntities.cs

public partial class UserLogin : IdentityUserLogin<Guid>
{
}
public partial class UserRole : IdentityUserRole<Guid>
{
}
public partial class UserClaim : IdentityUserClaim<Guid>
{
}
public partial class Role : IdentityRole<Guid>
{
    public Role() : base()
    { 
    }

    public Role(string roleName)
    {
        Name = roleName;
    }
}
public partial class RoleClaim : IdentityRoleClaim<Guid>
{
}
public partial class UserToken : IdentityUserToken<Guid>
{
}

配置服务

services.AddIdentity<User, Role> 

添加了这个并且有效:

builder.Entity<IdentityUserRole<Guid>>().HasKey(p => new { p.UserId, p.RoleId });

最常见的原因

Cannot create a DbSet for 'THE-MODEL' because this type is not included in the model for the context

如下

  1. 型号名称与数据库
  2. 中的 table 名称不匹配
  3. EntityFramework 无法按照惯例计算出所需的元数据,而您有 没有覆盖它。

在您的案例中,Role 继承了 IdentityRoleClaim 并且未配置,默认约定需要 "Id" 作为键,但我想它没有那个 属性,因此必须对其进行配置。如果您在像 Id => new{UserId,RoleId} 这样的 Role 中创建了 属性 ,它也会起作用,按照惯例,它将 Id 作为 属性 到 entity framework 的键 entity framework.

我遇到了类似的问题,这是由于我的 IUserStore 配置不正确造成的。我正在使用 Autofac 进行依赖注入,此配置解决了我的问题:

var dbContextParameter = new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(IdentityDbContext),
                                                    (pi, ctx) => ctx.Resolve<DatabaseContext>());

  builder.RegisterType<UserStore<User, Role, DatabaseContext, Guid,UserClaim,UsersInRole,UserLogin,UserToken,RoleClaim>>()
            .As<IUserStore<User>>().WithParameter(dbContextParameter).InstancePerLifetimeScope();
        builder.RegisterType<CustomRoleStore>()
            //RegisterType<UserStore<User, Role, DatabaseContext, Guid,UserClaim,UsersInRole,UserLogin,UserToken,RoleClaim>>()
            .As<IRoleStore<Role>>().WithParameter(dbContextParameter).InstancePerLifetimeScope();

我的 databaseContext 从 IdentityDbContext 驱动

 public class DatabaseContext : IdentityDbContext<User, Role, Guid, UserClaim
    , UsersInRole, UserLogin, RoleClaim, UserToken
    >, IDatabaseContext

我所要做的就是创建一个用户存储并将其提供给我的 DI 以注入 signinmanager class

如果您的 DbContext 不继承 IdentityUserContext - 不要在 ConfigureServices 方法中使用 AddEntityFrameworkStores。将其替换为 AddUserStore 和 AddRoleStore,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services
        .AddIdentity<MyUserType, MyRoleType>(...)
        .AddUserStore<UserStore<MyUserType, MyRoleType, MyDbContextType, MyKeyType, MyUserClaimType, MyUserRoleType, MyUserLoginType, MyUserTokenType, MyRoleClaimType>>()
        .AddRoleStore<RoleStore<MyRoleType, MyDbContextType, MyKeyType, MyUserRoleType, MyRoleClaimType>>();
    ...
}

如果您检查 AddEntityFrameworkStores 方法的实现,您会发现它通过在 DbContext 中搜索泛型类型来添加商店,假设它继承了 IdentityUserContext。无论如何,您将被声明的基本 Identity* 类型困住……这将生成此异常。

检查您的 AppDbContext 不是继承自 DbContext,而是应该继承自 IdentityDbContext<ApplicationUser>

我遇到了这个问题。为了修复它,我在我的实体配置中做了一些更改 Class。

public class AspNetUserClaimsConfig : IEntityTypeConfiguration<IdentityUserClaim<string>>
{
    public void Configure(EntityTypeBuilder<IdentityUserClaim<string>> builder)
    {
        builder.ToTable("AspNetUserClaims", "Identity");

        // Primary key
         builder.HasKey(uc => uc.Id);
    }
}

在我的上下文中,我这样做了:

public class IdentityContext : DbContext
{
    public IdentityContext(DbContextOptions<IdentityContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new ApplicationUsersConfig());

        base.OnModelCreating(modelBuilder);
    }
} 

我通过添加解决了这个问题:

public DbSet<ApplicationRole> ApplicationRoles { get; set; }

给我的 DbContext.

使用模型构建器在 DBContext 中添加您的模型。 如下所示编写您的数据库上下文 class。

 public partial class CDBContext : DbContext
   {

    public CDBContext (string ConnectionString) : base(new DbContextOptionsBuilder().UseSqlServer(ConnectionString).Options)
    {

    }  
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Query<MediaData>();            
    }

您可以通过替换这个来解决问题

public class ApplicationDbContext : IdentityDbContext<AppUser>

有了这个

public class ApplicationDbContext : IdentityDbContext<AppUser, AppRole, string>

注意最后一个参数中的这个字符串类型。

在我的例子中,我向 EF DbContext 传递了 错误的 class。我有 2 个 class,第一个 "Accounting",第二个 "Account"。我发送了“Accounting”,EF-Dbcontext 没有实体并返回

Cannot create a DbSet for 'Accounting' because this type is not included in the model for the context.

请勾选您要发送到 DbContext.

的 class
  1. 您需要检查您的 AppDbContext 是否继承自 IdentityDbContext。您的 AppDbContext 必须继承自 IdentityDbContext。

  2. 然后 OnModelCreating 你需要像下面这样映射关系 -

    builder.Entity<ApplicationUserRole>(userRole =>
         {
             userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
    
             userRole.HasOne(ur => ur.Role)
                 .WithMany(r => r.UserRoles)
                 .HasForeignKey(ur => ur.RoleId)
                 .IsRequired();
    
             userRole.HasOne(ur => ur.User)
                 .WithMany(r => r.UserRoles)
                 .HasForeignKey(ur => ur.UserId)
                 .IsRequired();
         });
    
  3. 整个应用程序数据库上下文看起来像 -

           using Core.Entities.Identity;
           using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
           using Microsoft.EntityFrameworkCore;
    
           namespace Infrastructure.Identity
           {
               public class AppIdentityDbContext : IdentityDbContext<AppUser, ApplicationRole, 
               string, IdentityUserClaim<string>,
               ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, 
               IdentityUserToken<string>>
               {
                  public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : 
                  base(options)
             {
             }
    
             protected override void OnModelCreating(ModelBuilder builder) 
             {
                base.OnModelCreating(builder);
    
                 builder.Entity<ApplicationUserRole>(userRole =>
                 {
                     userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
    
                     userRole.HasOne(ur => ur.Role)
                         .WithMany(r => r.UserRoles)
                         .HasForeignKey(ur => ur.RoleId)
                         .IsRequired();
    
                     userRole.HasOne(ur => ur.User)
                         .WithMany(r => r.UserRoles)
                         .HasForeignKey(ur => ur.UserId)
                         .IsRequired();
                 });
    
              }
           }
        }
    

    希望你的问题能得到解决。

我遇到了同样的问题,但我发现我没有将它包含在 RoleStoreUserStore 中 所以,您需要执行以下操作 在 ApplicationDbContext

public class ApplicationDbContext: IdentityDbContext<User, Role, GUID, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{}

您需要在店铺中添加Role、UserRole如下:

  1. 创建一个 class 从 RoleStore 继承如下

    public class AppRoleStore : RoleStore<Role, ApplicaitonDbContext, GUID, UserRole, RoleClaim>{}

2) 为 UserStore 创建 class,如下所示

public class AppUserStore : UserStore<User, Role, ApplicationDbContext, GUID, UserClaim, UserRole, UserLogin, UserToken, RoleClaim>
    {}

我也遇到了这个错误,这里有使用 EF Core 5.0 和 EF Core 6.0 的指南: