ASP.NET 核心 6 命名连接字符串未找到

ASP.NET Core 6 named connection string not found

我在新的 ASP.NET Core MVC 网络应用程序中使用 .NET 6 和 Entity Framework Core 6。我在用户机密中设置了连接字符串。我能够执行

dotnet ef dbcontext scaffold Name=ConnectionStrings:someconn 

没有任何问题。我的模型上下文已创建。现在我想做一个简单的查询,但是 program.cs 中的构建器抱怨找不到连接。

这里我创建一个生成器

var builder = WebApplication.CreateBuilder(args);

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

builder.Configuration
    .SetBasePath(currentDirectory)
    .AddUserSecrets<Program>()
    .AddEnvironmentVariables();

var connectionString = builder.Configuration.GetConnectionString("ConnectionStrings:someconn ");

这里我将此代码放在 program.cs 中,就在 app.Run 之前。

using (var ctx = new ModelContext())
{
    List<SomeModel> pd = ctx.SomeModel
        .Where(p => p.Id == "12345").ToList();

}

app.Run();

错误

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

更改以下代码

var connectionString = builder.Configuration.GetConnectionString("ConnectionStrings:someconn ");

var connectionString = builder.Configuration.GetConnectionString("someconn");

我本地可以用,你可以试试。另请注意,您的代码中有一个额外的 space。

这是从 appsettings.json 读取连接字符串的示例。 (为简单起见,我使用了一个 sqlite 示例,这不应该影响他们读取字符串的一般方式。)

希望这对您有所帮助。

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.AspNetCore": "Information"
    }
  },
  "ConnectionStrings": {
    "someconn": "Data Source=some.sqlite"
  }
}

和 Program.cs

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("someconn")

原因可能是找不到 appsettings.json。也许检查这部分代码是否需要或在读取连接字符串后执行它。

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("someconn")


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

builder.Configuration
    .SetBasePath(currentDirectory)//check if this is necessary
    .AddUserSecrets<Program>()
    .AddEnvironmentVariables();