首页 > 解决方案 > EF Core 2.1 身份表在 HasData() 播种后为空

问题描述

我正在尝试使用 EF Core 2.1 HasData 模式播种我的身份表,代码执行但没有任何内容插入到表中。
我的 DBContext 类代码:

public partial class IdentityDBContext : IdentityDbContext<IdentityUser>
{
    public IdentityDBContext(DbContextOptions<IdentityDBContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        IdentityRole RootRole = new IdentityRole 
        { 
            Id = Guid.NewGuid().ToString(), 
            Name = IdentityDBContext.RoleTypes.RootAdmin, 
            NormalizedName = "Root Admin" 
        };
        builder.Entity<IdentityRole>().HasData(RootRole);

        IdentityUser AdminUser = new IdentityUser 
        { 
            Id = Guid.NewGuid().ToString(), 
            UserName = "m@soze.biz", 
            Email = "m@soze.biz", 
            NormalizedUserName = "m@soze.biz".ToUpper(), 
            NormalizedEmail = "m@soze.biz".ToUpper(), 
            EmailConfirmed = true 
        };
        builder.Entity<IdentityUser>().HasData(AdminUser);

        builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string> 
        { 
            UserId = AdminUser.Id, 
            RoleId = RootRole.Id 
        });
    }
}

在 Configure 方法的 Startup.cs 中,我有:

using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
    var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<IdentityDBContext>();
    IdentityContext.Database.Migrate();
}

我可以OnModelCreating毫无例外地逐步执行代码,但是没有记录被添加到表中,两者AspNetUsers都是AspNetRoles空的。

关于为什么这不起作用的任何建议?

标签: c#asp.net-coreasp.net-identityef-core-2.1

解决方案


对于您的问题,是因为Migrate只应用了挂起的迁移,更改后它不会检测到更改IdentityDBContext

当您创建项目时Identity,它会自动创建第一个迁移,然后即使您更改了IdentityDBContextMigrate也只会应用第一个迁移而无需您进行其他操作。

这里有两个选择:

  • 对于第一次初始化数据库,您可以尝试下面的代码来播种数据。

            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            IdentityContext.Database.EnsureCreated();
        }
    
  • 第二个选项是您已经尝试过。在运行之前Migrate,运行Add-Migration以生成新更改的迁移。


推荐阅读