英文:
How to Intialize Database with entitycore in dotnet 7
问题
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
builder.Services.AddDbContext<TvMazeContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<TvMazeContext>();
DbInitializer.InitializeAsync(context).Wait(); // Wait for initialization to complete
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
// Rest of your program.cs code
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
英文:
I have written a class like bellow that should initialize the database
using System.Diagnostics;
using TvApi.Models;
using TvApi.Services;
namespace TvApi.Data
{
public static class DbInitializer
{
static List<List<Cast>> listedCasts;
static List<List<ShowCast>> listedShowCasts;
static List<Show> listedShows;
public static async Task InitializeAsync(TvMazeContext context)
{
for (long i= 1;i < 10; i++)
{
long ShowId = i;
Show show = await Crawler.CrawlShowAsync(ShowId);
listedShows.Add(show);
List<Cast> casts = await Crawler.GetCastsAsync(ShowId);
listedCasts.Add(casts);
List<ShowCast> showCasts = new List<ShowCast>();
foreach (var item in casts)
{
showCasts.Add(new ShowCast(show.ShowId, item));
}
listedShowCasts.Add(showCasts);
}
context.Database.EnsureCreated();
if (context.shows.Any())
{
return; // DB has been seeded
}
foreach (Show s in listedShows)
{
context.shows.Add(s);
}
context.SaveChanges();
foreach (List<Cast> castsList in listedCasts)
{
foreach(Cast cast in castsList)
{
context.casts.Add(cast);
}
}
foreach (List<ShowCast> showCastsList in listedShowCasts)
{
foreach (ShowCast showCast in showCastsList)
{
context.showCasts.Add(showCast);
}
}
}
}
}
I am following the microsoft tutorial bellow to add the intializer to my startup.cs
However the program.cs there is different than mine:
//My version of program.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TvApi.Data;
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
//Database
builder.Services.AddDbContext<TvMazeContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
/*
* My attempt to initialize
var host = CreateHostBuilder(args).Build();
IHost host;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<TvMazeContext>();
await DbInitializer.InitializeAsync(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
*/
// 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 the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
What should I add to my version of the program.cs to correctly initialize my database during the startup?
答案1
得分: 1
从你的问题中,我认为你想在数据库中种子数据,所以这里有一个简单的演示可以适用于 .Net6 和 .Net7
public static class DbInitializer
{
public static async Task InitializeAsync(ApplicationDbContext context)
{
List<SeedModel> seedDatas = new List<SeedModel>();
seedDatas.Add(new SeedModel()
{
Name = "AAAA",
Age = 2
});
seedDatas.Add(new SeedModel()
{
Name = "BBB",
Age = 3
});
seedDatas Add(new SeedModel()
{
Name = "AAAA",
Age = 2
});
await context.SeedModels.AddRangeAsync(seedDatas);
await context.SaveChangesAsync();
}
}
然后在 program.cs
中:
// ......
var app = builder.Build();
// ......
using (var scope = app.Services.CreateScope())
{
// 通过 DI 解析 dbcontext
var dbcontext = (ApplicationDbContext)scope.ServiceProvider.GetService(typeof(ApplicationDbContext));
// 调用你的静态方法
await DbInitializer.InitializeAsync(dbcontext);
}
// ......
现在,当你启动项目时,数据库将被初始化为一些数据。
英文:
From you question, I think You want to seed data in database, So here is a simple demo can fit .Net6 and .Net7
public static class DbInitializer
{
public static async Task InitializeAsync(ApplicationDbContext context)
{
List<SeedModel> seedDatas = new List<SeedModel>();
seedDatas.Add(new SeedModel()
{
Name = "AAAA",
Age = 2
});
seedDatas.Add(new SeedModel()
{
Name = "BBB",
Age = 3
});
seedDatas.Add(new SeedModel()
{
Name = "AAAA",
Age = 2
});
await context.SeedModels.AddRangeAsync(seedDatas);
await context.SaveChangesAsync();
}
}
Then in program.cs
//.......
var app = builder.Build();
//.....
using (var scope = app.Services.CreateScope())
{
//Resolve dbcontext with DI help
var dbcontext = (ApplicationDbContext)scope.ServiceProvider.GetService(typeof(ApplicationDbContext));
//call your static method herer
await DbInitializer.InitializeAsync(dbcontext);
}
//......
Now, When you start your project, Database will be initialized with some data.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论