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

001*_*001 24 c# asp.net asp.net-mvc .net-2.0 asp.net-identity

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

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

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

var result = await _signInManager.PasswordSignInAsync(model.Email, 
                                model.Password, model.RememberMe, lockoutOnFailure: false);
Run Code Online (Sandbox Code Playgroud)

怎么了?


User.cs

public partial class User : IdentityUser<Guid>
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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>
{
}
Run Code Online (Sandbox Code Playgroud)

ConfigureServices

services.AddIdentity<User, Role> 
Run Code Online (Sandbox Code Playgroud)

001*_*001 12

添加了这个,它工作:

builder.Entity<IdentityUserRole<Guid>>().HasKey(p => new { p.UserId, p.RoleId });
Run Code Online (Sandbox Code Playgroud)

  • 当我这样做时,在SQL Server数据库中创建一个新表"IdentityUserRole <Guid>".我已经添加了builder.Entity <UserRole>().HasKey(ur => new {ur.UserId,ur.RoleId}),为什么还不够? (2认同)
  • 添加到哪里了? (2认同)

Gur*_*eet 9

最常见的原因

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

如下面所述

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

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


Mun*_*suf 8

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

public class ApplicationDbContext : IdentityDbContext<AppUser>

有了这个

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

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


May*_*lor 7

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


小智 5

如果您的 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>>();
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果您检查 AddEntityFrameworkStores 方法的实现,您将看到它通过在 DbContext 中搜索泛型类型来添加存储,假设它继承了 IdentityUserContext。无论如何,您将被用于声明的基本 Identity* 类型卡住......这将产生此异常。