首页 > 解决方案 > 从 IDesignTimeDbContextFactory 访问 App.config

问题描述

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

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-frameworkentity-framework-coreef-code-firstentity-framework-migrations

解决方案


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

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


推荐阅读