Mik*_*ley 5 c# asp.net-identity asp.net-core ef-core-2.1
我试图使用 EF Core 2.1 HasData 模式为我的 Identity 表添加种子,代码执行但没有任何内容插入到表中。
我的 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
});
}
}
Run Code Online (Sandbox Code Playgroud)
在 Startup.cs 的配置方法中,我有:
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var IdentityContext = serviceScope.ServiceProvider.GetRequiredService<IdentityDBContext>();
IdentityContext.Database.Migrate();
}
Run Code Online (Sandbox Code Playgroud)
我可以单步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();
}
Run Code Online (Sandbox Code Playgroud)第二个选项是您已经尝试过的。在运行之前Migrate,运行Add-Migration以生成新更改的迁移。