执行EF Core update-database时遇CultureNotFoundException错误求助
update-database时的CultureNotFoundException错误 问题场景
在Visual Studio Community 2022(64位)预览版17.8.0 Preview 1.0中,基于ASP.NET Core Web API(EF Core 7.0.11)项目,执行包管理器控制台命令update-database时出现以下错误:
Build started...
Build succeeded.
System.Globalization.CultureNotFoundException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-us is an invalid culture identifier.
...(错误堆栈信息省略)
相关代码
APIContext.cs
using Componente.Pessoa; using Microsoft.EntityFrameworkCore; using System.Diagnostics; public class APIContext : DbContext, IPessoaContext { public DbSet<Pessoa> dbPessoas { get; set; } public DbSet<Cliente> dbClientes { get; set; } public DbSet<Endereco> dbEnderecos { get; set; } public IConfiguration _configuration; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Initial Catalog=OmnesProducao;;Integrated Security=True;TrustServerCertificate=True;User Id=sa;Password=pass;", builder => { }); base.OnConfiguring(optionsBuilder); } public APIContext() { } public APIContext(DbContextOptions<APIContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { PessoaContext.CarregaModel(modelBuilder); } }
Program.cs
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); AppContext.SetSwitch("System.Globalization.Invariant", true); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
解决方案
移除全球化不变模式设置:删除Program.cs中的
AppContext.SetSwitch("System.Globalization.Invariant", true);代码行。该开关强制程序仅使用不变文化,而SQL Server连接过程中需要加载特定文化(如en-us),二者冲突导致错误。修复DbContext注册与连接字符串:
- 在Program.cs的服务注册阶段添加APIContext的依赖注入配置,替换原有的硬编码配置:
builder.Services.AddDbContext<APIContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); - 在appsettings.json中配置正确的连接字符串(避免硬编码,同时修复认证方式冲突问题,二选一即可):
"ConnectionStrings": { "DefaultConnection": "Server=localhost\\SQLEXPRESS;Initial Catalog=OmnesProducao;Integrated Security=True;TrustServerCertificate=True;" // 或使用SQL认证:"Server=localhost\\SQLEXPRESS;Initial Catalog=OmnesProducao;User Id=sa;Password=pass;TrustServerCertificate=True;" } - 移除APIContext中OnConfiguring方法的硬编码连接字符串,让依赖注入接管配置。
- 在Program.cs的服务注册阶段添加APIContext的依赖注入配置,替换原有的硬编码配置:
优化APIContext构造函数:移除无参构造函数,确保EF Core工具优先使用带
DbContextOptions<APIContext>参数的构造函数,避免配置混乱。重新执行迁移命令:清理项目并重新生成,再次在包管理器控制台执行
update-database命令。
内容的提问来源于stack exchange,提问作者Maicon Cardozo

