3
私は最初のシステムロールでAspNetRoleテーブルをシードしようとしています。シードasp.netコアアイデンティティロール
播種拡張:起動クラスで呼び出される
public static void EnsureRolesAreCreated(this IApplicationBuilder app) {
Dictionary<string, string> roles = new Dictionary<string, string>
{
{ "Administrator", "Global Access." },
{ "User", "Restricted to business domain activity." }
};
var context = app.ApplicationServices.GetService<ApplicationDbContext>();
if (context.AllMigrationsApplied()) {
var roleManager = app.ApplicationServices.GetService<ApplicationRoleManager>();
foreach (var role in roles) {
if (!roleManager.RoleExistsAsync(role.Key).Result) {
roleManager.CreateAsync(new ApplicationRole() { Name = role.Key, System = true, Description = role.Value });
}
}
}
}
:アプリapp.EnsureRolesAreCreated();
実行上記のコードは、CreateAsync機能が例外をスロー:
{Microsoft.EntityFrameworkCore .DbUpdateException:エントリの更新中にエラーが発生しました。詳細については、内部例外を参照してください。 ---> System.Data.SqlClient.SqlException:列 'Id'、テーブル 'AspNetRoles'に値NULLを挿入できません。列はNULLを許可しません。 INSERTは失敗します。 ステートメントが終了しました。
services.AddIdentity<ApplicationUser, ApplicationRole>(config => {
config.User.RequireUniqueEmail = true;
config.Lockout = new LockoutOptions {
AllowedForNewUsers = true,
DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30),
MaxFailedAccessAttempts = 5
};
config.Password = new PasswordOptions {
RequireDigit = true,
RequireNonAlphanumeric = false,
RequireUppercase = true,
RequireLowercase = true,
RequiredLength = 12,
};
})
.AddEntityFrameworkStores<ApplicationDbContext, int>()
.AddUserValidator<ApplicationUserValidator<ApplicationUser>>()
.AddUserManager<ApplicationUserManager>()
.AddRoleManager<ApplicationRoleManager>()
.AddDefaultTokenProviders();
public class ApplicationUser : IdentityUser<int> {}
public class ApplicationRole : IdentityRole<int> {}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<ApplicationUser>(i => {
i.HasKey(x => x.Id);
i.Property(x => x.Id).ValueGeneratedOnAdd();
});
modelBuilder.Entity<ApplicationRole>(i => {
i.HasKey(x => x.Id);
i.Property(x => x.Id).ValueGeneratedOnAdd();
});
modelBuilder.Entity<IdentityUserRole<int>>(i => {
i.HasKey(x => new { x.RoleId, x.UserId });
});
modelBuilder.Entity<IdentityUserLogin<int>>(i => {
i.HasKey(x => new { x.ProviderKey, x.LoginProvider });
});
modelBuilder.Entity<IdentityRoleClaim<int>>(i => {
i.HasKey(x => x.Id);
i.Property(x => x.Id).ValueGeneratedOnAdd();
});
modelBuilder.Entity<IdentityUserClaim<int>>(i => {
i.HasKey(x => x.Id);
i.Property(x => x.Id).ValueGeneratedOnAdd();
});
}
IDを強制的に生成するために、ValueGeneratedOnAdd()
を追加しました。