【发布时间】:2018-11-20 01:02:28
【问题描述】:
我正在尝试使用 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 都是空的。
关于为什么这不起作用的任何建议?
【问题讨论】:
-
添加 has 数据代码后是否创建了新的 EF 迁移?
-
我确实在添加 HasData 代码后尝试添加迁移,但似乎我没有重新运行应用程序来推出该迁移。我知道这是我想念的简单的东西,谢谢阿曼!万一其他人遇到这个问题并遇到同样的问题,我在包管理器中运行“Add-Migration Update-Database -Context IdentityDBContext”,然后执行应用程序并将迁移推送到数据库。
标签: c# asp.net-core asp.net-identity ef-core-2.1