我正在尝试使用 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
代码,没有异常,但是没有记录添加到表中,AspNetUsers
和 AspNetRoles
都是空的.
关于为什么这不起作用的任何建议?
最佳答案
对于您的问题,这是因为 Migrate
仅应用了挂起的迁移,在您更改 IdentityDBContext
后它不会检测到更改。
当您使用 Identity
创建项目时,它会自动创建第一个迁移,然后即使您更改了 IdentityDBContext
,Migrate
也会仅在没有其他操作的情况下应用第一次迁移。
这里有两种选择:
对于第一次初始化数据库,您可以尝试下面的代码来播种数据。
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/