Я получаю эту ошибку только при вызове метода расширения SeedDatabase из Configure в Startup.cs. Если я прокомментирую эту строку, все работает хорошо.
Вот метод Configure из Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.SeedDatabase(); // if comment this works!
}
Существует класс расширения IApplicationBuilder с методом SeedDatabase.
public static class ApplicationBuilderExtensions
{
private const string DefaultAdminEmail = "admin@gmail.com";
private const string DefaultAdminPassword = "admin";
private const string DefaultUserEmail = "user@gmail.com";
private const string DefaultUserPassword = "user";
private static readonly IdentityRole[] defaultRoles = new IdentityRole[]
{
new IdentityRole(RoleName.Admin),
new IdentityRole(RoleName.Member),
};
public static async void SeedDatabase(this IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<User>>();
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
await SeedRoles(roleManager);
await SeedUsers(userManager, roleManager);
}
}
private static async Task SeedRoles(RoleManager<IdentityRole> roleManager)
{
foreach (var role in defaultRoles)
{
var roleExist = await roleManager.RoleExistsAsync(role.Name);
if (!roleExist)
{
await roleManager.CreateAsync(role);
}
}
}
private static async Task SeedUsers(UserManager<User> userManager, RoleManager<IdentityRole> roleManager)
{
var adminUser = await userManager.FindByEmailAsync(DefaultAdminEmail);
var memberUser = await userManager.FindByEmailAsync(DefaultUserEmail);
if (adminUser == null)
{
adminUser = new User()
{
UserName = DefaultAdminEmail,
Email = DefaultAdminEmail
};
await userManager.CreateAsync(adminUser, DefaultAdminPassword);
}
if (memberUser == null)
{
memberUser = new User()
{
UserName = DefaultUserEmail,
Email = DefaultUserEmail
};
await userManager.CreateAsync(memberUser, DefaultUserPassword);
}
await userManager.AddToRoleAsync(adminUser, RoleName.Admin);
await userManager.AddToRoleAsync(memberUser, RoleName.Member);
}
}