【问题标题】:Cannot create a DbSet for 'IdentityUser' because this type is not included in the model for the context无法为“IdentityUser”创建 DbSet,因为此类型未包含在上下文模型中
【发布时间】:2019-07-10 01:17:40
【问题描述】:

尝试使用所有代码来获取所有用户的角色,因此我不得不稍微更改我的代码并遇到此错误。我不确定我做错了什么,我把它缩小到我的 startup.cs 和 ApplicationDBContect 类。我没有错误,我可能需要迁移,没有这样做以防止导致更多问题。

我引用了Stackoverflow question 并有其他错误。

ApplicationDBContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> 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();
        });
    }

    public DbSet<ApplicationUser> ApplicationUser { get; set; }
}

Startup.cs

services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

【问题讨论】:

  • services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()改成services.AddIdentity&lt;IdentityUser, ApplicationRole&gt;()试试

标签: c# asp.net-core


【解决方案1】:

我看到您分别使用ApplicationUserApplicationRole 扩展IdenityUserIdentityRole,但您没有在身份服务注册中添加它们。所以在启动时更新你的身份服务注册如下:

services.AddIdentity<ApplicationUser, ApplicationRole>() // </-- here you have to replace `IdenityUser` and `IdentityRole` with `ApplicationUser` and `ApplicationRole` respectively
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

【讨论】:

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