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

A named connection string was used, but the name 'DefaultConnection' was not found in the application's configuration

我的 DOTNET 6 API:

中有一个名为 FileManagerContextDbContext
public class FileManagerContext : DbContext {
    public FileManagerContext(DbContextOptions<FileManagerContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
    }
}

这是一个非常简单的 DbContext,其中包含一个简单的实体。不管怎样,我也有这个 appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=FM;User=SA;Password=1234;"
  },
  "AllowedHosts": "*"
}

下面是 Program.cs 的顶级语句中的启动片段:

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

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

System.InvalidOperationException: A named connection string was used, but the name 'DefaultConnection' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

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

var cs = builder.Configuration.GetConnectionString("DefaultConnection");

但它 returns 无效。有人可以帮我解决吗?

从错误的声音来看,您的配置可能没有被提取。

如何创建配置?

您是否看到在 Webhost 上调用了 AddConfiguration 扩展方法?该方法的内容应如下所示:

IConfiguration config = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", false, false)                                           
                          .AddJsonFile($"appsettings.{envLower}.json", true, true)
                          .AddEnvironmentVariables()
                          .Build();

构建调用可能存在也可能不存在。我们通常手动创建配置对象,因为我们需要构建记录器,然后使用 AddConfiguration 扩展方法将该对象添加到主机。

如果您没有看到,请查看 Microsoft 的文档以获取有关如何设置它的指导。 Configuration Documentation

或者,您可以通过配置对象获取连接字符串并将其传递给 UseSqlServer 方法。

services.AddDbContext<FileManagerContext>((provider, options) => {
           IConfiguration config = provider.GetRequiredService<IConfiguration>();
           string connectionString = config.GetConnectionString("DefaultConnection");
           options.UseSqlServer(connectionString);                             
         });

在备用方法中,将服务提供者传递给操作。您可以使用提供程序从 DI 容器中获取 IConfiguration 对象。

不要使用“name=DefaultConnection”,因为它被视为包含“name=”的连接字符串名称

我在 program.cs 中使用此语法并且一切正常

var builder = WebApplication.CreateBuilder(args);

.......

builder.Services.AddDbContext<FileManagerContext>(options => 
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

并且由于您使用的是 Ms Sql 服务器,sql 服务器的连接字符串通常是这样的

"DefaultConnection": "Data Source=xxxx;Initial catalog=xxx;Integrated Security=False;User ID=xxxx;Password=xxxx;"

我的 OnConfiguring 代码如下所示

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
   if (!optionsBuilder.IsConfigured)
   {
       ...your code
    }
}

使用builder.Configuration

builder.Services.AddDbContext<FileManagerContext>(options => 
{
    options.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"]);
});

builder.Configuration.GetConnectionString如@Serge所述

options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

感谢 我弄明白了。配置未加载到应用程序中。但是,由于我在 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"));