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

ASP.NET Core 6执行Update-Database时初始化字符串格式错误求助

解决EF Core迁移报错:Format of the initialization string does not conform to specification starting at index 0

你的问题根源在于连接字符串的读取和配置错误,以下是具体修复步骤:

1. 修正Program.cs中的连接字符串键名

在Program.cs里,你调用configuration.GetConnectionString("DefaultConnections")时,键名多了一个s,而appsettings.json中定义的键是DefaultConnection,导致读取到空值,引发格式错误。

修改后的代码:

builder.Services.AddDbContext<ApplicationDBContext>(options =>
    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

2. 修复DesignTimeDbContextFactory的连接字符串配置

ApplicationDBContextFactory是EF Core设计时工具(如Update-Database)会用到的类,当前代码里用的是占位符"your connection string",必须替换为实际的连接字符串,或者通过配置文件读取:

方法一:直接替换为实际连接字符串

public class ApplicationDBContextFactory : IDesignTimeDbContextFactory<ApplicationDBContext>
{
    public ApplicationDBContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDBContext>();
        // 替换成你appsettings里的连接字符串
        optionsBuilder.UseSqlServer("Data Source=LAPTOP-T70EVGQC\\MSSQLSERVER01;Initial Catalog=MoviesApi;Integrated Security=True;");

        return new ApplicationDBContext(optionsBuilder.Options);
    }
}

方法二:从配置文件读取(更规范)

添加Microsoft.Extensions.Configuration包后,通过ConfigurationBuilder读取appsettings.json:

public class ApplicationDBContextFactory : IDesignTimeDbContextFactory<ApplicationDBContext>
{
    public ApplicationDBContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDBContext>();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));

        return new ApplicationDBContext(optionsBuilder.Options);
    }
}

3. 验证连接字符串格式

确认appsettings.json中的连接字符串格式正确:

  • 实例名LAPTOP-T70EVGQC\\MSSQLSERVER01是否正确(可在SQL Server Management Studio中查看实例名称)
  • Integrated Security=True确保使用Windows身份验证,若使用SQL Server身份验证,需替换为User ID=xxx;Password=xxx;

完成以上修复后,重新执行Update-Database命令,即可正常创建Genres表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:35:59