[英]ASP.NET Core Web API - seeding data in .NET Core 6 using Entity Framework
在 ASP.NET Core 6 Web API 中,我正在實施 EF 遷移播種。 當我使用 .NET Core 5 時,我將它應用到Startup.cs
中,它在那里工作。
public static class AppDbContextSeed
{
public static void SeedData(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
SeedRoles(roleManager);
SeedUsers(userManager);
}
public static void SeedRoles(RoleManager<ApplicationRole> roleManager)
{
if (!roleManager.RoleExistsAsync("Admin").Result)
{
ApplicationRole role = new ApplicationRole();
role.Name = "Admin";
IdentityResult roleResult = roleManager.
CreateAsync(role).Result;
}
if (!roleManager.RoleExistsAsync("Student").Result)
{
ApplicationRole role = new ApplicationRole();
role.Name = "Student";
IdentityResult roleResult = roleManager.
CreateAsync(role).Result;
}
}
public static void SeedUsers(UserManager<ApplicationUser> userManager)
{
if (userManager.FindByNameAsync("admin").Result == null)
{
ApplicationUser user = new ApplicationUser()
{
UserName = "admin",
Email = "admin@africa.email.com",
FirstName = "AdminFN",
LastName = "AdminLN",
NormalizedUserName = "ADMIN"
};
IdentityResult result = userManager.CreateAsync
(user, "Admin*123").Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user, "Admin").Wait();
}
}
}
}
但是現在我正在使用 .NET Core 6。所以當我在Program.cs
中應用它時:
public void Configure(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
// DB Seeding
AppDbContextSeed.SeedData(userManager, roleManager);
}
我收到此錯誤:
聲明了本地 function 'Config' 但從未使用過
錯誤 CS0106:修飾符“public”對此項目無效
如何更正錯誤並將其復制到 .NET Core 6 中?
謝謝你。
我不得不編輯我的最后一個答案,我給出的示例是針對 .net5 的。 這是 .net 6,我自己沒有測試過,但應該可以。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
Configure(app);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
void Configure(WebApplication host)
{
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var dbContext = services.GetRequiredService<MyDatabaseContext>();
if (dbContext.Database.IsSqlServer())
{
dbContext.Database.Migrate();
}
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
AppDbContextSeed.SeedData(userManager, roleManager);
}
catch (Exception ex)
{
//Log some error
throw;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.