简体   繁体   English

如何从 DBContext(实体框架核心)中的 App.config(不是 .net 核心应用程序)中读取值

[英]How to read value from App.config (not .net core app) in DBContext (which is entity framework core)

I'm using my old application (Standard .net framework wpf app) with new entity framework core.我正在使用带有新实体框架核心的旧应用程序(标准 .net 框架 wpf 应用程序)。

在此处输入图像描述 I've set up connection to database by hardcoding connection string here:我在这里通过硬编码连接字符串建立了与数据库的连接:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
   optionsBuilder.UseSqlServer(@"server=baaa;database=baaa;User=saaa;Password=xsaa1;");
}

But I would like to move my connection string to App.config or somewhere else and read it from there instead of keeping it hardcoded.但我想将我的连接字符串移动到 App.config 或其他地方并从那里读取它而不是将其硬编码。

Since my WPF app is not .net core WPF app I can't use DI to write something like this:由于我的 WPF 应用程序不是 .net 核心 WPF 应用程序我不能使用 DI 来写这样的东西:

IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

So question is how to read connection string from my old WPF (.NET FRAMEWORK) App in DbContect of entity framework core?那么问题是如何在实体框架核心的 DbContect 中从我的旧 WPF (.NET FRAMEWORK) 应用程序读取连接字符串?

Thanks谢谢

Cheers干杯

You can use Microsoft's ConfigurationManager It exists both in .net core and .net framework.你可以使用微软的 ConfigurationManager它既存在于 .net core 中,也存在于 .net framework 中。 at .net core you can add simply from nuget, and at.framework just add the system.configuration dll在 .net 核心,您可以简单地从 nuget 添加,而 at.framework 只需添加 system.configuration dll

read app-setting:读取应用程序设置:

 var version=ConfigurationManager.AppSettings["APP_SETTING_KEY"].ConnectionString;

read connection string:读取连接字符串:

 var cs =ConfigurationManager.ConnectionStrings["YOUR_CS_KEY"].ConnectionString;

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

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