[英]Connection string based on location (c# + asp.net)
I've got 3 connection strings in my app: 我的应用程序中有3个连接字符串:
<add name="DBConnectionString" connectionString=""/>
<add name="ADConnectionString" connectionString="" />
<add name="TestDBConnectionString" connectionString="" />
now in the code i do: 现在在代码中我做了:
public static string DefaultConnection
{
get
{
// this is used so that there will be no chance of modifing the original data when testing locally
if (HttpContext.Current.Server.MachineName == "xxx")
return ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString;
else
return ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
}
}
and this works in code behind, but when I do ordinary SqlDataSource and then do i like this: 这在后面的代码中有效,但是当我执行普通的SqlDataSource然后执行以下操作时:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%# DBConnections.DefaultConnection %>" />
I get: The ConnectionString property has not been initialized.
我得到: ConnectionString属性尚未初始化。 What am I doing wrong?
我究竟做错了什么? AFAIK this should get the value I want...
AFAIK这应该得到我想要的值...
I don't want to do in connections section as I WANT TO BE SURE that I don't mess up the production server since I'm in the same network... I could do the whole publishing project but that's waaaaaaaaaaaay too much work.
我不想在连接部分中做,因为我想确保不会弄乱生产服务器,因为我在同一个网络中……我可以完成整个发布项目,但这太过麻烦了。
Unless you are databinding the container the SqlDataSource is in, the <%# %>
syntax won't work (because that's binding syntax, and the property is never bound), so your issue is that the ConnectionString property just isn't getting set at all. 除非您对SqlDataSource所在的容器进行数据绑定,否则
<%# %>
语法将不起作用(因为这是绑定语法,并且该属性从未绑定),所以您的问题是ConnectionString属性只是未设置完全没有
I'd set this in the codebehind, or alternatively, have a completely different config for production. 我将在后面的代码中进行设置,或者使用完全不同的配置进行生产。 For the code behind:
对于后面的代码:
SqlDataSource1.ConnectionString = DBConnections.DefaultConnection;
One more option is, if you use the same connection in tons of places, just make a control that inherits from SqlDataSource and override the ConnectionString property, set it only in that getter/setter and just use that control everywhere instead. 另一个选择是,如果您在大量地方使用相同的连接,只需创建一个从SqlDataSource继承并覆盖ConnectionString属性的控件,仅在该getter / setter中进行设置,然后在各处使用该控件即可。
Something like: 就像是:
public class MySqlDataSource : SqlDataSource
{
public string _customConnectionStr; //Allow a custom connection still
public override string ConnectionString {
//Default the connection if a custom isn't set
get { return _customConnectionStr ?? DBConnections.DefaultConnection; }
set { _customConnectionStr = value; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.