简体   繁体   English

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

[英]How to use proper connection string .net core console application

I have scenario where I have to expand my project with .NET CORE WEB API PROJECT.我有一个场景,我必须使用 .NET CORE WEB API PROJECT 扩展我的项目。

In the beginning it was just console app which was working as a windows service on a simple tasks, adding data from xml files to database.一开始它只是一个控制台应用程序,它作为 windows 服务在一个简单的任务上工作,将 xml 文件中的数据添加到数据库中。

And my structure looks like this:我的结构如下所示:

  1. Database Project (ENTITY FRAMEWORK CORE)数据库项目(实体框架核心)
  2. Console App ( REFERENCING TO DATABASE PROJECT)控制台应用程序(参考数据库项目)
  3. Web Api (REFERENCING TO DATABASE PROJECT) Web Api(参考数据库项目)

Now when I created WEB API project it requires me to register Context in Startup.cs and I did it like this:现在,当我创建 WEB API 项目时,它要求我在 Startup.cs 中注册 Context,我是这样做的:

Startup.cs启动.cs

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

And that is all fine.这一切都很好。

But now I want to read connection string for console application for it's own connection string ( appsettings.json ) since when I created API it got his own appsettings.json where I'm storing connection string for WEB API. But now I want to read connection string for console application for it's own connection string ( appsettings.json ) since when I created API it got his own appsettings.json where I'm storing connection string for WEB API.

My DBContext looks like this:我的 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;");
}

In my console app I have add appsettings.json在我的控制台应用程序中,我添加appsettings.json

在此处输入图像描述

And here is my Program.cs :这是我的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);
    }
}

And here is how I use Context in my console application:以下是我在控制台应用程序中使用 Context 的方式:

using (var context = new ProductXmlDBContext())
{
    companies = context.Companies.ToList();
}

And probably because of this usage it uses value from protected override void OnConfiguring method instead from its own appsettings.json ?并且可能由于这种用法,它使用来自protected override void OnConfiguring方法的值,而不是来自它自己的appsettings.json

So how could I read connection string for this console application only from itself appsettings.json (to remove/avoid using hardcoded value) from context.那么我如何才能从上下文中appsettings.json (以删除/避免使用硬编码值)读取此控制台应用程序的连接字符串。

Edit:编辑:

There is no GetConnectionString option:没有GetConnectionString选项:

在此处输入图像描述

Thanks a lot!非常感谢!

Cheers干杯

One option I can suggest is to create another DBContextClass in your console application and just override the OnConfiguring method to read from appsettings of console application project我可以建议的一个选项是在您的控制台应用程序中创建另一个 DBContextClass 并覆盖 OnConfiguring 方法以从控制台应用程序项目的 appsettings 中读取

Example: New Class in Console Application示例:控制台应用程序中的新 Class

public class ConsoleProductXmlDBContext : ProductXmlDBContext
    {
        private readonly IConfiguration _iConfiguration;
        private readonly string _connectionString;

        public ConsoleProductXmlDBContext()
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            _iConfiguration = builder.Build();
            _connectionString = _iConfiguration.GetConnectionString("DefaultConnection");
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            _ = optionsBuilder.UseSqlServer(_connectionString, providerOptions => providerOptions.CommandTimeout(60))
                          .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
        }
    }

Usage in Console Application在控制台应用程序中的使用

using (var context = new ConsoleProductXmlDBContext())
{
    companies = context.Companies.ToList();
}

Check the documentation here: https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.onconfiguring?view=efcore-5.0在此处查看文档: https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.onconfiguring?view=efcore-5.0

In situations where an instance of DbContextOptions may or may not have been passed to the constructor, you can use IsConfigured to determine if the options have already been set, and skip some or all of the logic in OnConfiguring(DbContextOptionsBuilder).在 DbContextOptions 的实例可能已传递或未传递给构造函数的情况下,您可以使用 IsConfigured 来确定选项是否已设置,并跳过 OnConfiguring(DbContextOptionsBuilder) 中的部分或全部逻辑。

So you can check the IsConfigured value and do nothing if options have been provided already.因此,您可以检查IsConfigured值,如果已提供选项,则不执行任何操作。

The proper solution though, would be to have the overridden function read from the configuration directly, if there is no reason to override it at the first place.但是,正确的解决方案是让被覆盖的 function 直接从配置中读取,如果没有理由首先覆盖它。

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-5.0#publish-to-a-folder The published folder will contain the proper configuration file, depending on which application you published. https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-5.0#publish-to-a-folder发布的文件夹将包含正确的配置文件,具体取决于您发布了哪个应用程序。

暂无
暂无

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

相关问题 如何在 .Net core 控制台应用程序中使用依赖注入 - How to use Dependency Injection in .Net core Console Application .NET控制台应用程序连接字符串转换 - .NET Console Application Connection String Transformation 是否可以在.Net Core 2控制台应用程序中使用WCF? - Is it possible to use WCF in a .Net Core 2 console application? 在.NET Core应用程序中获取连接字符串 - Get connection string in .NET Core application 在自托管的.net core 2.2应用程序上正确使用IsDevelopement() - Proper use of IsDevelopement() on self hosted .net core 2.2 application 现在可以在从 Windows 任务调度程序运行 .net 核心控制台应用程序时读取 appsettings.json 文件中存在的连接字符串 - Now able to read the Connection String present in appsettings.json file when running the .net core Console application from windows task scheduler ASP.NET 5控制台应用程序(程序包)-如何从连接字符串创建DBContext? - ASP.NET 5 Console Application (package) - How to create DBContext from connection string? 如何读取 .NET Core 中的连接字符串? - How to read connection string in .NET Core? 我可以在 dot net core 控制台应用程序中使用 BackgroundService - Can I use BackgroundService in dot net core console application 如何在控制台应用程序(.Net Core 2.2)中使用带有DinkToPdf(wkhtmltopdf)的.css文件? - How to use .css file with DinkToPdf (wkhtmltopdf) in console application (.Net Core 2.2)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM