【问题标题】:Is it possible/advisable to seed Users/Roles using the EFCore 2.1 Data Seeding system?是否可以/建议使用 EFCore 2.1 数据播种系统播种用户/角色?
【发布时间】:2018-06-07 13:39:49
【问题描述】:
【问题讨论】:
标签:
asp.net-core
entity-framework-core
【解决方案1】:
如果您想将OnModelCreating 方法与HasData 方法一起使用,您可以这样做:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
ApplicationUser appUser = new ApplicationUser
{
UserName = "tester",
Email = "tester@test.com",
NormalizedEmail = "tester@test.com".ToUpper(),
NormalizedUserName = "tester".ToUpper(),
TwoFactorEnabled = false,
EmailConfirmed = true,
PhoneNumber = "123456789",
PhoneNumberConfirmed = false
};
PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>();
appUser.PasswordHash = ph.HashPassword(appUser, "Your-PW1");
modelBuilder.Entity<IdentityRole>().HasData(
new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
new IdentityRole { Name = "User", NormalizedName = "USER"}
);
modelBuilder.Entity<ApplicationUser>().HasData(
appUser
);
}
如果您在HasData 方法之外创建用户,则可以使用PasswordHasher。
它将为您散列密码。然后只需将创建的用户放入HasData,而不是在那里创建一个新用户。
我不知道这是否比启动时播种更好,但这是一种方法。
【讨论】:
-
这确实比seeding on startup 好,正如微软所说的The seeding code should not be part of the normal app execution,但他们也说.HasData() 不应该用于Data that requires calls to external API, such as ASP.NET Core Identity roles and users creation docs.microsoft.com/en-us/ef/core/modeling/…