c# - 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
空的。
关于为什么这不起作用的任何建议?
解决方案
对于您的问题,是因为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
以生成新更改的迁移。
推荐阅读
- php - 更改 PHP 数组中条目的键
- azure-devops - 如何将 Azure DevOps Extension for Azure CLI 与 Azure DevOps Server 一起使用?
- react-native - 从任何地方导航到子屏幕
- java - 使用正则表达式在字符串中搜索子字符串
- node.js - nodejs/vanilla 中的 Apollo-client 未触发订阅
- entity-framework - 为什么 IMutableEntityType.BaseType 对于直接从基类继承的实体为空?
- c# - Unity中未分配的变量
- azure - 使用任何配置禁用某些 Azure 功能
- elasticsearch - 创建索引时如何解决“无法解析内容以映射”错误?
- graphics - Graphics.set_font Ocaml