.NET Core 控制台应用程序,连接字符串存储在哪里

.NET Core console application, where is the connection string stored

Inside Visual Studio 2019 我创建了一个 .NET Core 控制台应用程序。然后我使用下面的命令映射现有数据库 -

PM> Scaffold-DbContext "Server=.\MSSQL;Database=SchoolDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

以上命令映射了SchoolDB数据库中的所有表。但我有以下问题 -

  1. 在我的 asp.net 核心 Web 应用程序中,连接字符串保存在哪里?因此,当我将控制台应用程序从测试环境移至实时环境时,我可以更改它。

这是我的控制台应用程序在 运行 上述命令后的样子,我找不到任何配置文件来存储连接字符串 -

Scaffold-DbContext 命令应该在名为 SchoolDBContext.cs 的文件中创建一个 class SchoolDBContext 并且它应该放在您用 [=17= 指定的目录中] 命令中的参数。此 class 有一个 OnConfiguring 方法,其中连接字符串定义为 -

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

如果想让SchoolDBContext放在单独的目录下,可以在命令中使用-ContextDir参数指定,如-

Scaffold-DbContext "your_connection_string" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir DbContext

编辑:
如果要将连接字符串放入配置文件 -

  1. 在项目的根目录下添加一个.json文件(例如appconfig.json),并在其中放入以下内容-
{
  "ConnectionStrings": {
    "myDbConn": "your_connection_string"
  }
}
  1. 在解决方案资源管理器中,右键单击 appconfig.json 文件和 select Properties。将 Copy to Output Directory 的值设置为 Copy Always.
  2. 安装 Microsoft.Extensions.Configuration.Json 软件包
  3. 修改OnConfiguring方法为-
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var config = new ConfigurationBuilder()
        .AddJsonFile("appconfig.json", optional: false).Build();

    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer(config.GetConnectionString("myDbConn"));
    }
}