繁体   English   中英

ASP.NET 找不到 Core 6 命名连接字符串

[英]ASP.NET Core 6 named connection string not found

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

dotnet ef dbcontext scaffold Name=ConnectionStrings:someconn 

没有任何麻烦。 我的 model 上下文已创建。 现在我想做一个简单的查询,但是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();

错误

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

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

希望这可以帮助。

应用程序设置.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();

更改以下代码

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

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

它在我的本地有效,你可以试试。 另请注意,您的代码中有一个额外的空间。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM