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

.NET Core 6中‘DefaultConnection’命名连接字符串配置报错求助

解决方法

方法1:给Plataforma DbContext添加带DbContextOptions的构造函数

生成的DbContext默认只有无参构造,导致DI注册的配置没被正确识别,IsConfigured一直为false。你需要手动给Plataforma类添加一个接收DbContextOptions<Plataforma>的构造函数:

public class Plataforma : DbContext
{
    public Plataforma(DbContextOptions<Plataforma> options) : base(options)
    {
    }

    // 保留原来的DbSet和其他生成的代码
    // ...

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("name=DefaultConnection");
        }
    }
}

添加这个构造函数后,DI容器实例化Plataforma时会传入你在Program.cs里配置的DbContextOptions,此时optionsBuilder.IsConfigured会变为true,不会再执行OnConfiguring里的命名连接字符串逻辑。

方法2:修改OnConfiguring方法,注入IConfiguration获取配置

如果不想调整构造函数,也可以给DbContext注入IConfiguration,直接从配置中读取连接字符串:

首先修改Plataforma的构造函数:

private readonly IConfiguration _configuration;

public Plataforma(IConfiguration configuration)
{
    _configuration = configuration;
}

// 若需要单独测试可保留无参构造
public Plataforma()
{
}

然后修改OnConfiguring逻辑:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
    }
}

这样即使触发OnConfiguring逻辑,也能正确读取配置中的连接字符串,避免报错。

方法3:重新生成DbContext时禁用OnConfiguring生成

下次执行Scaffold-DbContext命令时,加上--no-onconfiguring参数,生成的DbContext会自动适配DI配置,不再包含OnConfiguring方法:

Scaffold-DbContext "name=DefaultConnection" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models --no-onconfiguring

生成的DbContext会自带接收DbContextOptions的构造函数,直接和你在Program.cs里的DI配置配合使用,不会出现配置冲突。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:05:28