ASP.NET Core 6中dbContext.Database.EnsureCreated()的正确放置位置
问题:ASP.NET启动时无法自动创建数据库,手动迁移命令正常
相关技术方案适用于早期版本的ASP.NET。使用Add-Migration InitialCreate和Update-Database命令可正确创建数据库,但无法实现应用启动时自动创建数据库,运行时出现错误提示。
相关代码
DotNet.P001.L07.MainProject > Program.cs
using DotNet.P001.L14.Database; using Microsoft.EntityFrameworkCore; namespace DotNet.P001.L07.MainProject; public class Program { public static void Main(string[] args) { var AngularCorsPolicy = "_angularCorsPolicy"; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer( builder.Configuration.GetConnectionString("ApplicationContext") ?? throw new InvalidOperationException("Connection string 'ApplicationContext' not found."))); builder.Services.AddCors(options => { options.AddPolicy(AngularCorsPolicy, policy => { policy.WithOrigins( "https://localhost:44472", "https://localhost:7218" ) .AllowAnyHeader(); ; }); }); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Create database if it does not exist ApplicationDbContext dbContext = app.Services.GetRequiredService<ApplicationDbContext>(); dbContext.Database.EnsureCreated(); // Configure the HTTP request pipeline. if(!app.Environment.IsDevelopment()) { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(AngularCorsPolicy); app.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); app.MapFallbackToFile("index.html"); app.Run(); } }
DotNet.P001.L14.Database > ApplicationDbContext.cs
using DotNet.P001.L14.Database.Entities; using Microsoft.EntityFrameworkCore; namespace DotNet.P001.L14.Database; public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<MessageEntity>? Message { get; set; } }
DotNet.P001.L14.Database > Entities > MessageEntity.cs
namespace DotNet.P001.L14.Database.Entities; public class MessageEntity { public int Id { get; set; } public string? Content { get; set; } public string? FirstNameAuthor { get; set; } public string? LastNameAuthor { get; set; } }
解决方案
经排查,原有代码存在问题,需将以下代码片段:
ApplicationDbContext dbContext = app.Services.GetRequiredService<ApplicationDbContext>(); dbContext.Database.EnsureCreated();
替换为:
using(var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); // EnsureDeleted() 是可选操作,会先删除已存在的数据库 dbContext.Database.EnsureDeleted(); dbContext.Database.EnsureCreated(); }
该方案参考微软官方文档《运行时应用迁移》的内容。
内容的提问来源于stack exchange,提问作者kzstack
相关产品推荐
相关产品推荐

