使用了命名连接字符串,但在应用程序的配置中找不到名称“DefaultConnection”

jav*_*iry 5 c# entity-framework-core .net-core .net-6.0 ef-core-6.0

我的 DOTNET 6 API 中有一个DbContext名称:FileManagerContext

public class FileManagerContext : DbContext {
    public FileManagerContext(DbContextOptions<FileManagerContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
    }
}
Run Code Online (Sandbox Code Playgroud)

它非常简单,DbContext里面有一个简单的实体。无论如何,我appsettings.json也有这个:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=FM;User=SA;Password=1234;"
  },
  "AllowedHosts": "*"
}
Run Code Online (Sandbox Code Playgroud)

这是Program.cs顶级声明中的启动片段:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<FileManagerContext>(
    opt => opt.UseSqlServer("name=DefaultConnection"));
Run Code Online (Sandbox Code Playgroud)

我可以在这种情况下使用迁移。一切顺利。我可以添加迁移并且可以成功更新数据库。但是当我运行该应用程序并尝试使用时,DbContext出现此错误:

System.InvalidOperationException:使用了命名连接字符串,但在应用程序的配置中找不到名称“DefaultConnection”。请注意,仅在使用“IConfiguration”和服务提供程序时才支持命名连接字符串,例如在典型的 ASP.NET Core 应用程序中。有关详细信息,请参阅 https://go.microsoft.com/fwlink/?linkid=850912 。

我也尝试过像这样获取连接字符串:

var cs = builder.Configuration.GetConnectionString("DefaultConnection");
Run Code Online (Sandbox Code Playgroud)

但它返回 null。有人可以帮助我吗?

jav*_*iry 0

感谢@Neil,我明白了。配置未加载到应用程序中。但是,由于我处于 dotnet 6 的顶级语句中,因此添加配置似乎与 @Neil 的建议有点不同。所以这是可行的解决方案:

builder.Services.AddControllers();

var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var environmentName = builder.Environment.EnvironmentName;

builder.Configuration
    .SetBasePath(currentDirectory)
    .AddJsonFile("appsettings.json", false, true)
    .AddJsonFile($"appsettings.{environmentName}.json", true, true)
    .AddEnvironmentVariables();

// blah blah 
builder.Services.AddDbContext<FileManagerContext>(
    opt => opt.UseSqlServer("name=DefaultConnection"));
Run Code Online (Sandbox Code Playgroud)