我现在一直在研究一个项目,该项目的生产版本在共享托管环境中运行,而在我的开发机器上运行。 这里的问题是,每次我想在我的开发机器上运行应用程序时,我都必须修改连接字符串设置以指向开发机器上的localDb,反之亦然。 这对我来说非常不方便,直到我想出这个至少完美运行的解决方案。 我的问题是,这是我的解决方案在Aspnet环境中的专业和可靠吗?或者,是否有更好和最有效的方法来更好地实现此解决方案?谢谢。请参阅代码了解详情。
//Created a static method in Global.asax.cs
/// <summary>
/// Returns Connection settings based on the machine. i.e, automatically select connection strings if it's development or live server
/// </summary>
/// <param name="ArrayIndex"></param>
/// <returns> string BaseConn = (connectionstring name) </returns>
public static string
Settings( int ArrayIndex)
{
string[] BaseConn ={ HttpContext.Current.Request.IsLocal ? System.Configuration.ConfigurationManager.ConnectionStrings[4].Name :
System.Configuration.ConfigurationManager.ConnectionStrings[1].Name,
//Identity database connections
HttpContext.Current.Request.IsLocal ? System.Configuration.ConfigurationManager.ConnectionStrings[5].Name :
System.Configuration.ConfigurationManager.ConnectionStrings[2].Name,
//store database connection
HttpContext.Current.Request.IsLocal ? System.Configuration.ConfigurationManager.ConnectionStrings[6].Name :
System.Configuration.ConfigurationManager.ConnectionStrings[3].Name,
};
return BaseConn[ArrayIndex];
}
然后我在DbContext类中调用了一个跟随
的方法public class MyAppDb :DbContext
{
public MyAppDb()
: base(MvcApplication.Settings(0))
{ }
// Some entity tables here
}
我为商店DbContext和Identity DbContext做了同样的事情。 在本地和现场机器上,一切似乎都很好用。虽然我无法使用codefirst迁移使用此解决方案更新数据库。至少现在不是问题。
答案 0 :(得分:1)
您需要使用Web.Release.Config。
在Web.config中,您将指定自己的(本地)连接字符串,在发布时您将使用类似的内容(根据您自己的SQL连接更改配置)。
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SalvaVidas;Server=ServerName;Database=MyDb;Trusted_Connection=True;Integrated Security=SSPI;"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
确保name属性在两者中都匹配。在这个例子中,它是:name =&#34; MyContext&#34;
注意:请确保在发布时,它将以RELEASE模式运行。
答案 1 :(得分:0)
您最好使用 Web.Config转换。
这个想法是,在部署时,您选择目标环境,配置文件将根据Web.{CONFIGURATION_NAME}.config
文件中描述的更改自动转换。
例如,要更改Release
配置的连接字符串,您需要在Web.Release.config
文件中使用此字符串:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyDB"
connectionString="{SQL_SERVER_CONNECTION_STRING_FOR_RELEASE}"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
请参阅Tutorial
答案 2 :(得分:0)
因此,当有人忘记(并且有人会)设置“释放”或“调试”模式时,您的系统将错误地点击开发数据或生产数据,这似乎是灾难的一个秘诀....这只是做似乎没有失败证明我。必须有一种方法将其编码到应用程序中。例如,您可以编写代码,以便您的应用程序确定它正在运行的服务器,如果是生产服务器则使用生产连接字符串....如果它是测试服务器则使用测试连接字符串,否则使用开发连接字符串