4

我正在寻找在使用实体框架时处理并发的最佳方法。这里描述了最简单和最推荐的(也在堆栈上)解决方案: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() 和第二个 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() 第二个参数传递什么:

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

是的,即使第二次保存也可能导致 OptimisticConcurrencyException - 正如您所说的那样 -Refresh()和之间发生了变化SaveChanges()

给出的示例只是一个非常简单的重试逻辑,如果您需要多次重试或以更复杂的方式解决冲突,您最好创建一个重试 n 次的循环,而不是嵌套 try/catch 更多单层。

于 2012-03-02T13:22:55.030 回答