【问题标题】:How to read value from App.config (not .net core app) in DBContext (which is entity framework core)如何从 DBContext(实体框架核心)中的 App.config(不是 .net 核心应用程序)读取值
【发布时间】:2020-12-18 03:51:00
【问题描述】:

我正在使用带有新实体框架核心的旧应用程序(标准 .net 框架 wpf 应用程序)。

我在这里通过硬编码连接字符串设置了与数据库的连接:

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

但我想将我的连接字符串移动到 App.config 或其他地方并从那里读取它,而不是保持硬编码。

由于我的 WPF 应用程序不是 .net 核心 WPF 应用程序,因此我不能使用 DI 编写如下内容:

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

那么问题是如何在实体框架核心的 DbContect 中从我的旧 WPF (.NET FRAMEWORK) 应用程序中读取连接字符串?

谢谢

干杯

【问题讨论】:

    标签: c# wpf entity-framework .net-core


    【解决方案1】:

    您可以使用Microsoft's ConfigurationManager 它同时存在于 .net 核心和 .net 框架中。 在 .net 核心,您可以简单地从 nuget 添加,而在 .framework 只需添加 system.configuration dll

    读取应用设置:

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

    读取连接字符串:

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

    【讨论】:

    • DbContext 在单独的项目中,所以我不确定它是否知道 appsettings?因为应用程序配置文件在另一个项目(WPF 项目)中?
    • 请检查我的编辑。我在那里发布了一张结构图。
    • 但由于该项目链接到您的主 WPF 之一,它应该知道使用它的配置。你试过了吗?
    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2017-10-01
    • 2020-05-16
    相关资源
    最近更新 更多