添加ADO.NET实体数据模型
的代码生成添加以下类和App.config文件。
public partial class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyDbContext")
{
}
应用程序配置
<connectionStrings>
<add name="MyDbContext"
connectionString="data source=...;initial catalog=...;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
但是,我已经将连接字符串保存在 Properties.Settings.Default.MyDbConnString
中。如何更改代码以使用属性中的代码?
最佳答案
注意 DbContext(String)
的构造函数参数名称构造函数
public DbContext(string nameOrConnectionString);
Constructs a new context instance using the given string as the name or connection string for the database to which a connection will be made
您可以在构造函数中使用完整的连接字符串,以便更新上下文以使用属性中存储的值。
public partial class MyDbContext : DbContext {
public MyDbContext()
: base(Properties.Settings.Default.MyDbConnString) {
}
}
并删除配置文件中的 on 以避免任何冲突。
关于c# - 不是从 App.Config 获取连接字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50400374/