초기 시스템 역할로 AspNetRole 테이블을 시드하려고합니다.시드 asp.net 핵심 신분 역할
시드 확장 : 응용 프로그램 실행 위의 코드는 CreateAsync 함수는 예외가 발생 app.EnsureRolesAreCreated();
:
{Microsoft.EntityFrameworkCore을 시작 클래스라고
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 }); } } } }
.DbUpdateException : 항목을 업데이트하는 동안 오류가 발생했습니다. 자세한 내용은 내부 예외를 참조하십시오. ---> System.Data.SqlClient.SqlException : 열 'ID', 테이블 'AspNetRoles'; NULL 값을 삽입 할 수 없습니다; 열이 널을 허용하지 않습니다. INSERT가 실패합니다. 명세서가 종료되었습니다.
나는 This과 this을 시도했지만 여전히 작동하지 않습니다.
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()
을 추가했습니다.