下面是我的种子班。
public static class DataInitializer
{
public static async void SeedRolesAsync(RoleManager<Role> roleManager)
{
if (roleManager.RoleExistsAsync("Administrator").Result)
return;
var role = new Role
{
Name = "Administrator",
Description = "Perform all the operations."
};
await roleManager.CreateAsync(role);
}
public static async void SeedRoleClaimsAsync(RoleManager<Role> roleManager)
{
var role = await roleManager.FindByNameAsync("Administrator");
var roleClaims = await roleManager.GetClaimsAsync(role);
foreach (var claimString in AllClaims.GetList())
{
var newClaim = new Claim(claimString, "");
if (!roleClaims.Any(rc => rc.Type.ToString() == claimString))
{
await roleManager.AddClaimAsync(role, newClaim);
}
}
}
public static async void SeedUsersAsync(UserManager<User> userManager)
{
var user = new User
{
UserName = "admin@example.com",
Email = "admin@example.com",
FirstName = "Admin",
LastName = "User",
Enabled = true
};
var result = await userManager.CreateAsync(user, "Admin@123");
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, "Administrator");
}
}
public static void SeedData(UserManager<User> userManager, RoleManager<Role> roleManager)
{
SeedRolesAsync(roleManager);
SeedRoleClaimsAsync(roleManager);
SeedUsersAsync(userManager);
}
}
在启动类DataInitializer.SeedData(userManager, roleManager);
中调用此方法
播种时,我得到的错误低于错误。.我正在使用ef core 3进行Postgresql ..我得到
System.ObjectDisposedException:'无法访问已处置的对象。 对象名称:“ MyUserManager”。
答案 0 :(得分:2)
尝试完全使用任务-如果您不退回任何东西等待机会,即使尚未完成,代码仍将继续处理。
public static async Task SeedData(UserManager<User> userManager, RoleManager<Role> roleManager)
{
await SeedRolesAsync(roleManager);
await SeedRoleClaimsAsync(roleManager);
await SeedUsersAsync(userManager);
}
public static async Task SeedRolesAsync(RoleManager<Role> roleManager)
{
⋮
}
public static async Task SeedRoleClaimsAsync(RoleManager<Role> roleManager)
{
⋮
}
public static async Task SeedUsersAsync(UserManager<User> userManager)
{
⋮
}
您也可以将此调用移至Main
的{{1}}方法中,因为可以将该方法设为Program.cs
。
async