我正在寻找在使用Entity Framework时处理并发的最佳方式。最简单和最推荐的(也是在stack上)解决方案在这里描述: http://msdn.microsoft.com/zh-cn/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吗?