[英]c# - Entity Framework ConnectionString won't update after changing App.Config in runtime
I'm developing a WPF application which depends on Entity Framework for data access.我正在开发一个 WPF 应用程序,它依赖于实体框架进行数据访问。 At the first time installation I need to create a new connection string based on the User input, then updating App.Config according to that.第一次安装时,我需要根据用户输入创建一个新的连接字符串,然后根据它更新 App.Config。
The problem is: after updating the App.Config file, Entity Framework doesn't detect the change and uses the old startup-time ConnectionString for instantiating the DbContext.问题是:更新 App.Config 文件后,Entity Framework 未检测到更改并使用旧的启动时 ConnectionString 来实例化 DbContext。
How can I update the Entity Framework's ConnectionString setting at runtime?如何在运行时更新实体框架的 ConnectionString 设置?
Entity Framework caches connection string, there isn't a method to force a refresh.实体框架缓存连接字符串,没有强制刷新的方法。
From this article : connection string given in DbContext
constructor isn't cached then you can use this as workaround:从这篇文章:在DbContext
构造函数中给出的连接字符串没有被缓存,那么你可以使用它作为解决方法:
public class MyContext : DbContext {
public MyContext()
: base(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString)
{
}
}
Had same issue today.今天有同样的问题。 Connection string is stored in cached App.Config file in obj folder.连接字符串存储在 obj 文件夹中缓存的 App.Config 文件中。
Solution: Delete obj folder.解决方法:删除obj文件夹。
I had the same error.我有同样的错误。 My new connection string was missing "Initial Catalog="我的新连接字符串缺少“初始目录=”
Global.cs全球.cs
public class Global
{
public static string ConnectionString=String.Empty;
}
Store connection string as temporary in Global.cs first time after connection string saved in App.config.在 App.config 中保存连接字符串后,第一次将连接字符串临时存储在 Global.cs 中。
DBContext.cs数据库上下文.cs
public class DBContext: DbContext
{
public DbSet<User> UserInfo { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
String.IsNullOrEmpty(Global.ConnectionString) ? ConfigurationManager.ConnectionStrings["your_connectionstring"].ConnectionString
: Global.ConnectionString
);
}
}
Firstly, you have already defined connection string in your App.config.首先,您已经在 App.config 中定义了连接字符串。 Hope you enjoy!希望你喜欢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.