如何使用正确的连接字符串.net core控制台应用程序

Rox*_*Pro 6 c# dbcontext entity-framework-core .net-core asp.net-core

我有一个场景,我必须使用 .NET CORE WEB API PROJECT 扩展我的项目。

一开始它只是控制台应用程序,它作为 Windows 服务执行简单的任务,将 xml 文件中的数据添加到数据库。

我的结构如下所示:

  1. 数据库项目(实体框架核心)
  2. 控制台应用程序(参考数据库项目)
  3. Web Api(参考数据库项目)

现在,当我创建 WEB API 项目时,它要求我在 Startup.cs 中注册 Context,我是这样做的:

启动.cs

// DbContext for MSSQL
services.AddDbContextPool<ProductXmlDBContext>(options => options.UseSqlServer(_configuration.GetConnectionString(Config.CONNECTION_STRING)));
Run Code Online (Sandbox Code Playgroud)

这一切都很好。

但现在我想读取控制台应用程序的连接字符串,因为它有自己的连接字符串(appsettings.json),因为当我创建 API 时,它有自己的appsettings.json连接字符串,我在其中存储 WEB API 的连接字符串。

我的 DBContext 看起来像这样:

public ProductXmlDBContext()
{

}
// I added this because it was required for WEB API to work
public ProductXmlDBContext(DbContextOptions<ProductXmlDBContext> options) : base(options)
{

}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(@"Server=localhost;Database=ProductXml;Trusted_Connection=True;");
}
Run Code Online (Sandbox Code Playgroud)

在我的控制台应用程序中我添加了appsettings.json

在此输入图像描述

这是我的Program.cs

static void Main(string[] args)
{
    try
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(AppContext.BaseDirectory))
            .AddJsonFile("appsettings.json", optional: true);

        var services = new ServiceCollection();

        Configuration = builder.Build();

        // 
        var x = Configuration.GetConnectionString("DefaultConnection");

        services.AddDbContextPool<ProductXmlDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我在控制台应用程序中使用 Context 的方式:

using (var context = new ProductXmlDBContext())
{
    companies = context.Companies.ToList();
}
Run Code Online (Sandbox Code Playgroud)

可能是因为这种用法,它使用protected override void OnConfiguring方法中的值而不是它自己的 appsettings.json值?

那么我如何才能从appsettings.json 上下文中仅从其自身读取此控制台应用程序的连接字符串(以删除/避免使用硬编码值)。

编辑:

没有GetConnectionString选择:

在此输入图像描述

多谢!

干杯

Ath*_*ras 0

检查此处的文档:https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.onconfiguring? view=efcore-5.0

在 DbContextOptions 实例可能已传递或未传递给构造函数的情况下,您可以使用 IsConfigured 来确定是否已设置选项,并跳过 OnConfiguring(DbContextOptionsBuilder) 中的部分或全部逻辑。

IsConfigured因此,如果已经提供了选项,您可以检查该值并且不执行任何操作。

不过,正确的解决方案是直接从配置中读取被重写的函数(如果没有理由首先重写它)。

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-5.0#publish-to-a-folder发布的文件夹将包含正确的配置文件,具体取决于您发布了哪个应用程序。