[英]Making connection string reference instead of hard coding
Currently, my application has connection strings hard coded. 当前,我的应用程序已对连接字符串进行了硬编码。
string connectionString2 = "Data Source=SWDB10DSQL;Initial Catalog=BillingUI;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework";
I'm trying to change it so I reference the connection string that is defined in the web.config file instead. 我正在尝试更改它,所以我改为引用web.config文件中定义的连接字符串。 I've tried a solution found on here below, however it's not working (data is not inserting into my table anymore).
我已经尝试过在下面找到一个解决方案,但是它不起作用(数据不再插入到我的表中)。 It compiles however.
但是它会编译。
ImportController.cs ImportController.cs
string connectionString2 = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["BillingUIEntities"].ConnectionString;
using (SqlConnection _con2 = new SqlConnection(connectionString2))
{
_con2.Open();
Web.config Web.config文件
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<add name="BillingUIEntities" connectionString="metadata=res://*/Models.Model2.csdl|res://*/Models.Model2.ssdl|res://*/Models.Model2.msl;provider=System.Data.SqlClient;provider connection string="data source=SWDB10DSQL;initial catalog=BillingUI;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
Update: I've determined that it is getting the connection string from Web.config, but it's including the meta data which linq/ my sql connection doesn't seem to want in the controller. 更新:我已经确定它是从Web.config获取连接字符串,但是它包含了linq /我的sql连接似乎不需要控制器中的元数据。 I thought sub stringing could be a work around but I don't think that's a good way of doing it cause the meta data can change, resulting in a longer/shorter length string which would cause me to substring an invalid region of the connection string.
我认为子字符串处理可以解决,但我认为这不是一种好方法,因为元数据可能会发生变化,导致字符串的长度变长或变短,这会导致我将连接字符串的无效区域变成子字符串。 Is there a better way to do this?
有一个更好的方法吗?
Use ConfigurationManager instead of WebConfgurationManager. 使用ConfigurationManager而不是WebConfgurationManager。
string connectionString2 = System.Configuration.ConfigurationManager.ConnectionStrings["BillingUIEntities"].ConnectionString;
:) David :) 大卫
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.