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

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

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

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

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

怎么了?


User.cs

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

IdentityEntities.cs

 public partial class UserLogin : IdentityUserLogin { } public partial class UserRole : IdentityUserRole { } public partial class UserClaim : IdentityUserClaim { } public partial class Role : IdentityRole { public Role() : base() { } public Role(string roleName) { Name = roleName; } } public partial class RoleClaim : IdentityRoleClaim { } public partial class UserToken : IdentityUserToken { } 

ConfigureServices

 services.AddIdentity 

添加了这个并且它有效:

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

最常见的原因

无法为“THE-MODEL”创建DbSet,因为此类型不包含在上下文的模型中

如下面所述

  1. 模型名称与数据库中的表名称不匹配
  2. EntityFramework无法按惯例找出所需的元素,并且您没有覆盖它。

在您的情况下,角色inheritanceIdentityRoleClaim并且未配置,默认约定需要“Id”作为密钥,但我认为它没有该属性,因此必须进行配置。 如果您在Role中创建了属性,例如Id => new {UserId,RoleId},它会按惯例将Id作为entity framework的关键属性。

我有类似的问题,这是来自IUserStore的错误配置。 我正在使用Autofac进行dependency injection,这个配置解决了我的问题:

 var dbContextParameter = new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(IdentityDbContext), (pi, ctx) => ctx.Resolve()); builder.RegisterType>() .As>().WithParameter(dbContextParameter).InstancePerLifetimeScope(); builder.RegisterType() //RegisterType>() .As>().WithParameter(dbContextParameter).InstancePerLifetimeScope(); 

我的databaseContext驱动来自IdentityDbContext

  public class DatabaseContext : IdentityDbContext, IDatabaseContext 

而我所要做的就是创建一个Userstore并将它提供给我的DI以注入signinmanager类

如果您的DbContext不inheritanceIdentityUserContext – 请勿在ConfigureServices方法中使用AddEntityFrameworkStores。 用AddUserStore和AddRoleStore替换它,如下所示:

 public void ConfigureServices(IServiceCollection services) { ... services .AddIdentity(...) .AddUserStore>() .AddRoleStore>(); ... } 

如果检查AddEntityFrameworkStores方法的实现,您将看到它通过在DbContext中搜索generics类型来添加存储,假设它inheritance了IdentityUserContext。 无论如何,你将会遇到声明的基本身份*类型……这将产生此exception。

检查您的AppDbContext是否未inheritance自DbContext ,而应inheritance自IdentityDbContext