简体   繁体   中英

Connection string based on location (c# + asp.net)

I've got 3 connection strings in my app:

<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:

  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%# DBConnections.DefaultConnection %>" />

I get: What am I doing wrong? AFAIK this should get the value I want...

I don't want to do in connections section as 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.

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.

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; } 
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM