從應用程序的其餘部分中抽取出可能存在多個數據庫的事實是很好的做法。
public class WidgetRepository
{
private readonly string _primaryConnectionString;
private readonly string _secondaryConnectionString;
public WidgetRepository(string primaryConnectionString, string secondaryConnectionString)
{
_primaryConnectionString = primaryConnectionString;
_secondaryConnectionString = secondaryConnectionString;
}
public void AddWidget(Widget widget)
{
ExecuteAction(AddWidgetAction(widget));
}
public void UpdateWidget(Widget widget)
{
ExecuteAction(UpdateWidgetAction(widget));
}
private Action<string> AddWidgetAction(Widget widget)
{
return Action<string>(connectionString => {
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Widgets(name, price) VALUES(@name, @price)";
command.Parameters.AddWithValue("@name", widget.Name);
command.Parameters.AddWithValue("@price", widget.Price);
command.ExecuteNonQuery();
}
}
});
}
private Action<string> UpdateWidgetAction(Widget widget)
{
// Logic here to update a widget
}
private void ExecuteAction(Action<string> action)
{
try
{
action(_primaryConnectionString);
}
catch (SqlException)
{
action(_secondaryConnectionString);
}
}
}
用法:
var widgetRepository = new WidgetRepository("dbconn1", "dbconn2");
widgetRepository.AddWidget(new Widget("Cog", 15.99m));
你有什麼打算時,你的數據在2個數據庫蔓延呢? – Matthew
本地數據庫中的數據將從另一個負責該特定任務的模塊複製到主數據庫。 – andreapier
有一些像故障轉移這樣的服務,但這是針對企業場景的,我認爲您最初想到的「SqlException」可能會起作用,但您應該嘗試將其從應用程序中提取出來。 – Matthew