c# - 从 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
.
如何在我的应用程序和我的设计时工厂之间共享相同的连接字符串,而无需手动维护两者?
解决方案
EF Core 在设计时实例化 DB 上下文,例如添加迁移或更新数据库,以收集有关实体的详细信息并映射它们。但是您的项目的 App.config 无法使用 ConfigurationManager 访问,因为 EF 核心设计时是另一个具有自己的应用程序设置的应用程序。
从我的答案中找到解决方案: https ://stackoverflow.com/a/65221508/2818667
推荐阅读
- python-3.x - 这个函数的返回值是直接到前端的吗?
- python - Folium 中的 HeatMapWithTime 插件
- python - 监视或重新启动 Raspberry Pi 上的 RFID 线程 - tkinter
- codenameone - 具有代号一的文件:///var/mobile/Media/DCIM/ 的只读访问权限
- c++ - 带有嵌套 if/else 的 switch 语句在 C++ 中提供多个输出
- angular - 如何在 http 调用 angular 中设置加载程序指示器
- api - Next JS - API 实用程序文件夹结构
- javascript - 如果选择了 2 个不同的收音机,做一些事情
- python-3.x - Python 3,Tkinter 帧销毁
- wordpress - 电子商务。使用 ajax 加载类别和产品的展示柜