【问题标题】:Cannot create a DbSet for 'IdentityRole' because this type is not included in the model for the context error无法为“IdentityRole”创建 DbSet,因为该类型未包含在上下文错误的模型中
【发布时间】:2019-01-04 02:09:41
【问题描述】:

您好,我想为我的 aspnetcore2.0 + postgresql 项目添加基于角色的身份验证。出于这个原因,我跟随 How to create roles in asp.net core and assign them to users

但我得到错误

无法为“IdentityRole”创建 DbSet,因为该类型未包含在上下文模型中

顺便说一句,我的 db 表中没有 identityrole 和 identityuser 表。

简单项目可以从http://eticaret.turkalpkucur.com/katmanliproje2.rar下载

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    选项 1。

    添加了这个并且它起作用了:

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

    选项 2。

    最常见的原因

    模型名与数据库中的表名不匹配 EntityFramework 无法按照约定找出所需的元数据,并且您没有覆盖它。 AppDbContext 不是从 DbContext 继承的,而是应该从 IdentityDbContext 继承 在 accountcontroller.cs 和 startup.cs 模型不匹配然后这种类型的问题已经发生例如

        public class Role : IdentityRole
        {       
        }
    

    在您的 DbContext.cs 中

        public class DataContext : IdentityDbContext<ApplicationUser, Role, string, IdentityUserClaim<string>, IdentityUserRole<string>,
        IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
        {
            public DbSet<Role> Role { get; set; }
            public DataContext(DbContextOptions<DataContext> options)
               : base(options)
            {
            } 
        }
    

    在你的 startup.cs 中

      services.AddIdentity<IdentityUser, IdentityRole>();
    

    在上面给出的,有一个不同的角色模型,所以这不起作用。你可以改startup.cs打电话

    替换

    services.AddIdentity<IdentityUser, IdentityRole>()
    

    services.AddIdentity<IdentityUser, Role>()
    

    因为您在 DataContext 中添加了 Role

    选项 3。

    检查您的AppDbContext 不是继承自DbContext,而是应该继承自IdentityDbContext&lt;ApplicationUser&gt;

    【讨论】:

      【解决方案2】:

      如果您的上下文称为 DBContext,则可能是命名空间错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-16
        • 2019-07-13
        • 2019-07-10
        • 1970-01-01
        • 2018-10-20
        • 2022-01-08
        • 1970-01-01
        • 2020-03-09
        相关资源
        最近更新 更多