简体   繁体   中英

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.

在此处输入图像描述 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.

Since my WPF app is not .net core WPF app I can't use DI to write something like this:

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?

Thanks

Cheers

You can use Microsoft's ConfigurationManager It exists both in .net core and .net framework. at .net core you can add simply from nuget, and at.framework just add the 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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