c# - 将连接字符串从 app.config 移动到 C# 中的代码

标签 c# winforms entity-framework app-config

我正在尝试使用 Entity Framework 并将它的连接字符串放入 app.config 中。我想将它移动到代码中,因为在这个开发阶段它对我来说更容易。

metadata=res://*/database.csdl|res://*/database.ssdl|res://*/database.msl;provider=System.Data.SqlClient;provider connection string= “数据源=计算机;初始目录=数据库;持久安全信息=True;用户 ID=用户;密码=Mabm@A;multipleactiveresultsets=True;App=EntityFramework”

如何让 Entity Framework 使用代码中的连接字符串而不是查看 app.config?或者,如果无法将参数传递给 app.config(如 dbnamedbuserdbpassword) ?

最佳答案

为此,您可以使用 EntityConnectionStringBuilderCheck here

public string GetConnectionString()
    {
        string connectionString = new EntityConnectionStringBuilder
        {
            Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = new SqlConnectionStringBuilder
            {
                InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
                DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
                IntegratedSecurity = false,
                UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
                Password = ConfigurationManager.AppSettings["SystemDBPassword"],
                MultipleActiveResultSets = true,
            }.ConnectionString
        }.ConnectionString;

        return connectionString;
    }

关于c# - 将连接字符串从 app.config 移动到 C# 中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970379/

相关文章:

c# - 文本框的计时器/刷新功能

asp.net - Stored Proc业务逻辑应该放在MVC中的哪里?

c# - 如何使 WHERE 子句中的项目可选?

c# - C# 中的 PriorityQueue 不适用于自定义比较器

c# - 在 C# 中将 double 正确格式化为字符串?

c# - 在正则表达式中排除匹配

c# - 从 .NEt 中的最大化选项卡中删除还原按钮

c# - 如何指定全局 HttpWebRequest 超时?

c# - 显示 .txt 文件中的随机行 - C#

wpf - 数据网格上的 Entity Framework CRUD 操作