4

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である必要がありますか?

4

1 に答える 1

4

はい、2回目の保存でも OptimisticConcurrencyException が発生する可能性がありRefresh()ますSaveChanges()

与えられた例は非常に単純な再試行ロジックです。複数回再試行する必要がある場合、またはより複雑な方法で競合を解決する必要がある場合は、try/catch をこれ以上ネストするよりも、n 回再試行するループを作成することをお勧めします。シングルレベル。

于 2012-03-02T13:22:55.030 に答える