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

如何解决ASP.NET Core EF中ConnectionString未初始化问题

解决EF Core执行update-database时"The ConnectionString property has not been Initialized"错误

以下是导致错误的问题点及修复方案:

1. 扩展方法中连接字符串获取方式错误

你的ConnectionConfiguration扩展方法里,调用config.GetConnectionString时传参错误,多了Name=前缀。GetConnectionString方法会自动从配置的ConnectionStrings节点下读取对应键值,只需传入键名即可。

修正后的扩展方法代码:

public static class ConnectionConfiguration
{
    public static void AddDbContextAndConfigurations(this IServiceCollection services, IWebHostEnvironment env, IConfiguration config)
    {
        services.AddDbContext<DefaultDbContext>(options =>
        {
            string connStr = config.GetConnectionString("DefaultDbConnection");
            options.UseSqlServer(connStr);
        });
    }
}

2. DefaultDbContext的OnConfiguring方法配置错误

当使用Package Manager Console执行迁移时,EF Core可能会直接实例化DefaultDbContext而不经过DI容器,此时OnConfiguring方法里的optionsBuilder.UseSqlServer("Name=DefaultDbConnection")并没有实际读取配置文件,而是把字符串"Name=DefaultDbConnection"当成了连接字符串,这显然无效。

修正后的OnConfiguring方法代码:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        // 加载配置文件获取连接字符串
        var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        
        var configuration = configBuilder.Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultDbConnection"));
    }
}

3. 额外检查项

  • 确保Package Manager Console的默认项目选择的是包含DefaultDbContext的项目(如果是分层架构)。
  • 确保启动项目中存在appsettings.json,且ConnectionStrings配置正确无误。
  • 如果DefaultDbContext位于单独的类库项目中,需要在该类库中添加appsettings.json,并设置其复制到输出目录属性为"始终复制"或"如果较新则复制"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:27:39