EntityFrameworkを使用しながら同時実行を処理するための最良の方法を探しています。最も単純で最も推奨される(スタック上にもある)ソリューションについては、次のとおりです。http: //msdn.microsoft.com/en-us/library/bb399228.aspx 次のようになります。
try
{
// Try to save changes, which may cause a conflict.
int num = context.SaveChanges();
Console.WriteLine("No conflicts. " +
num.ToString() + " updates saved.");
}
catch (OptimisticConcurrencyException)
{
// Resolve the concurrency conflict by refreshing the
// object context before re-saving changes.
context.Refresh(RefreshMode.ClientWins, orders);
// Save changes.
context.SaveChanges();
Console.WriteLine("OptimisticConcurrencyException "
+ "handled and changes saved");
}
しかし、それで十分ですか?Refresh()と2番目のSaveChanges()の間で何かが変更された場合はどうなりますか?キャッチされていないOptimisticConcurrencyExceptionがありますか?
編集2:
これが最終的な解決策になると思います。
int savesCounter = 100;
Boolean saveSuccess = false;
while (!saveSuccess && savesCounter > 0)
{
savesCounter--;
try
{
// Try to save changes, which may cause a conflict.
int num = context.SaveChanges();
saveSuccess = true;
Console.WriteLine("Save success. " + num.ToString() + " updates saved.");
}
catch (OptimisticConcurrencyException)
{
// Resolve the concurrency conflict by refreshing the
// object context before re-saving changes.
Console.WriteLine("OptimisticConcurrencyException, refreshing context.");
context.Refresh(RefreshMode.ClientWins, orders);
}
}
Refresh()がどのように機能するかを理解しているかどうかはわかりません。コンテキスト全体を更新しますか?はいの場合、なぜ追加の引数(エンティティオブジェクト)が必要なのですか?または、指定されたオブジェクトのみを更新しますか?たとえば、この状況では、Refresh()の2番目の引数として何を渡す必要がありますか。
Order dbOrder = dbContext.Orders.Where(x => x.ID == orderID);
dbOrder.Name = "new name";
//here whole the code written above to save changes
それはdbOrderである必要がありますか?