在ConnectionInfo中使用Web.Config的连接字符串

时间:2014-05-20 09:28:25

标签: c# sql asp.net-mvc connection-string

我想将定义到Web.Config文件中的连接字符串用于使用ConnectionInfo关键字的类代码。

我已将Web.Config文件中的连接字符串定义为::

 <connectionStrings>
  <add name="Connection_Report" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=servername;initial catalog=dbName;user id=username;password=password;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

在我的课程代码中,我想将其用于ConnectionInfo 目前我必须在conroller中将其定义为::

ConnectionInfo ConnInfo = new ConnectionInfo { ServerName = "servername", UserID = "UserID", Password = "Password", DatabaseName = "DatabaseName" };

但是我想从连接字符串定义到Web.Config文件中使用它。

1 个答案:

答案 0 :(得分:1)

这会对你有所帮助:

var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["yourConnectionString"].ConnectionString;

        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
        string dbName = builder.InitialCatalog;
        string dbDataSource = builder.DataSource;
        string userId = builder.UserID;
        string pass = builder.Password;

然后在ConnectionInfo

ConnectionInfo ConnInfo = new ConnectionInfo { ServerName = "dbDataSource", UserID = "userId", Password = "pass", DatabaseName = "dbName" };