c# - EF Core 2.1 身份表在 HasData() 播种后为空

标签 c# asp.net-core asp.net-identity ef-core-2.1

我正在尝试使用 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 
        });
    }
}

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

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

我可以单步执行 OnModelCreating 代码,没有异常,但是没有记录添加到表中,AspNetUsersAspNetRoles 都是空的.

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

最佳答案

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

当您使用 Identity 创建项目时,它会自动创建第一个迁移,然后即使您更改了 IdentityDBContextMigrate 也会仅在没有其他操作的情况下应用第一次迁移。

这里有两种选择:

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

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

关于c# - EF Core 2.1 身份表在 HasData() 播种后为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384778/

相关文章:

c# - 限制 .net 插件可以访问的内容

c# - Dot Net Entity Framework 数据库更新不会在 mysql 数据库中创建表

.net - 更新同版本号的Nuget包

asp.net-core - 如何在 AspNet.Core 2.1 中通过依赖注入(inject)添加 UserManager?

mysql - 'Extent1.Email' 中的未知列 'field list'

c# - asp.net identity 2.0 可以在它自己的项目中运行吗?

c# - 如何比较大的 JSON?

c# - 许多短命线程方法?

asp.net-core - 在 Google OAuth 流程中访问 EF DbContext

c# - 如何将 GeoJSON 数据绑定(bind)到 ASP.NET Core 中的参数?