如何在运行时

时间:2017-03-25 08:59:23

标签: c# entity-framework connection-string app-config

我想在" app.config"中更改由Entity Framework创建的连接字符串参数。运行时文件。 我已经可以创建另一个连接字符串并使用它,但我需要在app.config文件中保存此连接字符串,以便从现在开始,程序可以使用保存在app.config文件中的连接字符串作为默认连接字符串。 / p>

由于

2 个答案:

答案 0 :(得分:0)

您可以通过提供一个代码open the filefind the place来显示连接字符串,然后将其替换为新值,然后save the file

答案 1 :(得分:0)

首先,您应该在App.Config文件中设置连接字符串。例如,我为你的数据库设置了连接字符串,如你所见

<configuration>
  <connectionstrings>
    <add name="TestConnectionstring"
    connectionString="Data Source=.;Initial Catalog=CharityManagement;Integrated Security=True"/>
  </add></connectionstrings>
</configuration>

之后,使用以下代码在表单中使用连接字符串: 在表单中,您可以设置要使用的引用:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

然后,您可以使用ConnectionStrings属性从App.Config获取连接字符串。

var connectionString=ConfigurationManager.ConnectionStrings["TestConnectionstring"].ConnectionString;

您可以在Windows窗体和ASP.NET项目中使用此方法。