【问题标题】:Access App.config from IDesignTimeDbContextFactory<T>从 IDesignTimeDbContextFactory<T> 访问 App.config
【发布时间】:2020-05-15 02:26:53
【问题描述】:

为了通过 Entity Framework Core 执行迁移,我创建了一个设计时工厂,如 this article 中所述。目前,我已经实现了这个,这似乎有效:

public StudentContextCreateDbContext(string[] args)
{
    string connectionString = "Data Source=localhost;Initial Catalog=MyCatalog;Integrated Security=True;";
    var optionsBuilder = new DbContextOptionsBuilder<StudentContext>();
    optionsBuilder.UseSqlServer(connectionString);
    return new StudentContext(optionsBuilder.Options);
}

但是,我不希望使用硬编码的连接字符串。我试过这条线,从App.config得到它:

string connectionString = ConfigurationManager.ConnectionStrings["Local"].ConnectionString;

返回完全相同的连接字符串,只是来自App.config 文件。它在实际应用程序中有效,但是当我在设计时工厂使用它时,我得到了一个System.NullReferenceException

如何在我的应用程序和设计时工厂之间共享相同的连接字符串,而不需要手动维护两者?

【问题讨论】:

    标签: c# entity-framework entity-framework-core ef-code-first entity-framework-migrations


    【解决方案1】:

    EF Core 在设计时实例化 DB 上下文,例如添加迁移或更新数据库,以收集有关实体的详细信息并映射它们。但是您的项目的 App.config 无法使用 ConfigurationManager 访问,因为 EF 核心设计时是另一个具有自己的应用程序设置的应用程序。

    从我的回答中找到解决方案: https://stackoverflow.com/a/65221508/2818667

    【讨论】:

      猜你喜欢
      • 2012-11-07
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2011-08-24
      • 2010-12-23
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多