c# - 不是从 App.Config 获取连接字符串吗?

标签 c# entity-framework entity-framework-6

添加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/

相关文章:

c# - 在添加迁移期间忽略来自引用程序集的实体

c# - 在 C# 中捕获 javascript 事件

c# - 如何为存储为数组 [ticks,offset] 的 DatetimeOffset 创建 MongoDB TTL 索引?

entity-framework - 如何停止 Entity Framework 5 迁移添加 dbo。成键名?

.net - Entity Framework 是否支持并行异步查询?

c# - Entity Framework ——如何缓存和共享只读对象

c# - Watin 不会手动触发 .change() 事件

c# - 替换特定字符之间的数据

.net - 在 DDD 中将另一个模型与 Entity Framework 一起使用有什么好处

c# - EDMFunction 是如何工作的?