如何在.NET 7中使用Entity Framework Core初始化数据库

huangapple go评论112阅读模式
英文:

How to Intialize Database with entitycore in dotnet 7

问题

  1. var builder = WebApplication.CreateBuilder(args);
  2. ConfigurationManager configuration = builder.Configuration;
  3. builder.Services.AddDbContext<TvMazeContext>(options =>
  4. options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
  5. builder.Services.AddDatabaseDeveloperPageExceptionFilter();
  6. var app = builder.Build();
  7. using (var scope = app.Services.CreateScope())
  8. {
  9. var services = scope.ServiceProvider;
  10. try
  11. {
  12. var context = services.GetRequiredService<TvMazeContext>();
  13. DbInitializer.InitializeAsync(context).Wait(); // Wait for initialization to complete
  14. }
  15. catch (Exception ex)
  16. {
  17. var logger = services.GetRequiredService<ILogger<Program>>();
  18. logger.LogError(ex, "An error occurred creating the DB.");
  19. }
  20. }
  21. // Rest of your program.cs code
  22. app.UseHttpsRedirection();
  23. app.UseAuthorization();
  24. app.MapControllers();
  25. app.Run();
英文:

I have written a class like bellow that should initialize the database

  1. using System.Diagnostics;
  2. using TvApi.Models;
  3. using TvApi.Services;
  4. namespace TvApi.Data
  5. {
  6. public static class DbInitializer
  7. {
  8. static List&lt;List&lt;Cast&gt;&gt; listedCasts;
  9. static List&lt;List&lt;ShowCast&gt;&gt; listedShowCasts;
  10. static List&lt;Show&gt; listedShows;
  11. public static async Task InitializeAsync(TvMazeContext context)
  12. {
  13. for (long i= 1;i &lt; 10; i++)
  14. {
  15. long ShowId = i;
  16. Show show = await Crawler.CrawlShowAsync(ShowId);
  17. listedShows.Add(show);
  18. List&lt;Cast&gt; casts = await Crawler.GetCastsAsync(ShowId);
  19. listedCasts.Add(casts);
  20. List&lt;ShowCast&gt; showCasts = new List&lt;ShowCast&gt;();
  21. foreach (var item in casts)
  22. {
  23. showCasts.Add(new ShowCast(show.ShowId, item));
  24. }
  25. listedShowCasts.Add(showCasts);
  26. }
  27. context.Database.EnsureCreated();
  28. if (context.shows.Any())
  29. {
  30. return; // DB has been seeded
  31. }
  32. foreach (Show s in listedShows)
  33. {
  34. context.shows.Add(s);
  35. }
  36. context.SaveChanges();
  37. foreach (List&lt;Cast&gt; castsList in listedCasts)
  38. {
  39. foreach(Cast cast in castsList)
  40. {
  41. context.casts.Add(cast);
  42. }
  43. }
  44. foreach (List&lt;ShowCast&gt; showCastsList in listedShowCasts)
  45. {
  46. foreach (ShowCast showCast in showCastsList)
  47. {
  48. context.showCasts.Add(showCast);
  49. }
  50. }
  51. }
  52. }
  53. }

I am following the microsoft tutorial bellow to add the intializer to my startup.cs

Microsoft tutorial

However the program.cs there is different than mine:

  1. //My version of program.cs
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.Hosting;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.Hosting;
  7. using Microsoft.Extensions.Logging;
  8. using TvApi.Data;
  9. var builder = WebApplication.CreateBuilder(args);
  10. ConfigurationManager configuration = builder.Configuration;
  11. //Database
  12. builder.Services.AddDbContext&lt;TvMazeContext&gt;(options =&gt;
  13. options.UseSqlServer(configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
  14. builder.Services.AddDatabaseDeveloperPageExceptionFilter();
  15. /*
  16. * My attempt to initialize
  17. var host = CreateHostBuilder(args).Build();
  18. IHost host;
  19. using (var scope = host.Services.CreateScope())
  20. {
  21. var services = scope.ServiceProvider;
  22. try
  23. {
  24. var context = services.GetRequiredService&lt;TvMazeContext&gt;();
  25. await DbInitializer.InitializeAsync(context);
  26. }
  27. catch (Exception ex)
  28. {
  29. var logger = services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();
  30. logger.LogError(ex, &quot;An error occurred creating the DB.&quot;);
  31. }
  32. }
  33. */
  34. // Add services to the container.
  35. builder.Services.AddControllers();
  36. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  37. builder.Services.AddEndpointsApiExplorer();
  38. builder.Services.AddSwaggerGen();
  39. var app = builder.Build();
  40. // Configure the HTTP request pipeline.
  41. if (app.Environment.IsDevelopment())
  42. {
  43. app.UseSwagger();
  44. app.UseSwaggerUI();
  45. }
  46. app.UseHttpsRedirection();
  47. app.UseAuthorization();
  48. app.MapControllers();
  49. 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

  1. public static class DbInitializer
  2. {
  3. public static async Task InitializeAsync(ApplicationDbContext context)
  4. {
  5. List<SeedModel> seedDatas = new List<SeedModel>();
  6. seedDatas.Add(new SeedModel()
  7. {
  8. Name = "AAAA",
  9. Age = 2
  10. });
  11. seedDatas.Add(new SeedModel()
  12. {
  13. Name = "BBB",
  14. Age = 3
  15. });
  16. seedDatas Add(new SeedModel()
  17. {
  18. Name = "AAAA",
  19. Age = 2
  20. });
  21. await context.SeedModels.AddRangeAsync(seedDatas);
  22. await context.SaveChangesAsync();
  23. }
  24. }

然后在 program.cs 中:

  1. // ......
  2. var app = builder.Build();
  3. // ......
  4. using (var scope = app.Services.CreateScope())
  5. {
  6. // 通过 DI 解析 dbcontext
  7. var dbcontext = (ApplicationDbContext)scope.ServiceProvider.GetService(typeof(ApplicationDbContext));
  8. // 调用你的静态方法
  9. await DbInitializer.InitializeAsync(dbcontext);
  10. }
  11. // ......
  12. 现在,当你启动项目时,数据库将被初始化为一些数据。
英文:

From you question, I think You want to seed data in database, So here is a simple demo can fit .Net6 and .Net7

  1. public static class DbInitializer
  2. {
  3. public static async Task InitializeAsync(ApplicationDbContext context)
  4. {
  5. List&lt;SeedModel&gt; seedDatas = new List&lt;SeedModel&gt;();
  6. seedDatas.Add(new SeedModel()
  7. {
  8. Name = &quot;AAAA&quot;,
  9. Age = 2
  10. });
  11. seedDatas.Add(new SeedModel()
  12. {
  13. Name = &quot;BBB&quot;,
  14. Age = 3
  15. });
  16. seedDatas.Add(new SeedModel()
  17. {
  18. Name = &quot;AAAA&quot;,
  19. Age = 2
  20. });
  21. await context.SeedModels.AddRangeAsync(seedDatas);
  22. await context.SaveChangesAsync();
  23. }
  24. }

Then in program.cs

  1. //.......
  2. var app = builder.Build();
  3. //.....
  4. using (var scope = app.Services.CreateScope())
  5. {
  6. //Resolve dbcontext with DI help
  7. var dbcontext = (ApplicationDbContext)scope.ServiceProvider.GetService(typeof(ApplicationDbContext));
  8. //call your static method herer
  9. await DbInitializer.InitializeAsync(dbcontext);
  10. }
  11. //......

Now, When you start your project, Database will be initialized with some data.

如何在.NET 7中使用Entity Framework Core初始化数据库

huangapple
  • 本文由 发表于 2023年3月7日 17:13:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定