如何比较C#中的两个连接字符串

时间:2015-07-16 11:43:04

标签: c# asp.net-mvc

我在webconfig中有一个默认的连接字符串和一个Connectionstring,如下所示:

<add name="BAG_Zipcodes" connectionString="Password=;Persist Security Info=True;
     User ID=sa;Initial Catalog=e;Data Source=" />

但是如果那个连接字符串不在webconfig中。使用这个:

ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName];

所以我这样比较:

var zipcodeConnection = ConfigurationManager.ConnectionStrings["BAG_Zipcodes"];
            //zipcodeConnection = ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName];

if (zipcodeConnection == ConfigurationManager.ConnectionStrings["BAG_Zipcodes"] && zipcodeConnection != null)
    zipcodeConnection = ConfigurationManager.ConnectionStrings["BAG_Zipcodes"];

else if (zipcodeConnection == ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName] && zipcodeConnection != null) 
    zipcodeConnection = ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName];

但是如果我从webconfig中删除了这个连接字符串:add name =“BAG_Zipcodes

然后connectionstring始终为null。

谢谢

2 个答案:

答案 0 :(得分:3)

这可以通过使用合并声明来完成。

var zipcodeConnection = (ConfigurationManager.ConnectionStrings["BAG_Zipcodes"])
                      ?? ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName];

答案 1 :(得分:-1)

哦,我这样解决了:

var zipcodeConnection = ConfigurationManager.ConnectionStrings["BAG_Zipcodes"];


if (zipcodeConnection == ConfigurationManager.ConnectionStrings["BAG_Zipcodes"] && zipcodeConnection != null)
    zipcodeConnection = ConfigurationManager.ConnectionStrings["BAG_Zipcodes"];

else if (zipcodeConnection == null) 
    zipcodeConnection = ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName];