You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.Net Core MVC执行update-database报错:初始化字符串格式不符合规范

问题排查与解决

核心错误:硬编码连接字符串字面量

你的program.cs里,调用UseSqlServer时传的是字符串字面量"connectionString",而不是你获取到的变量connectionString。这会让EF Core把"connectionString"当成连接字符串来用,完全不符合SQL Server连接字符串的格式,直接触发了你看到的Format of the initialization string does not conform to specification错误。

其他两处问题

  1. DbContext泛型参数不匹配
    你写的是builder.Services.AddDbContext<db_name>(...),但你的数据库上下文类是DBxyz,这里类型必须对应,要改成AddDbContext<DBxyz>(...)。

  2. 没必要提前构建ServiceProvider获取配置
    你当前获取IConfiguration的方式绕了弯路,WebApplicationBuilder本身就有Configuration属性,直接用就行,避免提前构建ServiceProvider带来的潜在问题。

修正后的program.cs关键代码

// 直接通过builder获取配置,无需提前构建ServiceProvider
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DBxyz>(options =>
    options.UseSqlServer(connectionString)); // 传递变量,不是字符串字面量

额外验证点

确认appsettings.json里的server_name是你的SQL Server实例真实名称(比如本地实例常用.\SQLEXPRESS或localhost),db_name是你要创建的数据库名称,同时确保SQL Server服务处于运行状态。

执行完修正后,重新运行update-database即可正常执行。

内容的提问来源于stack exchange,提问作者user401

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:50:43