Dee*_*101 17 entity-framework-5
在context.SaveChanges()其中一个例外情况下处理几个潜在的异常时OptimisticConcurrency.有关此问题的Microsoft文档,请访问http://msdn.microsoft.com/en-us/library/bb399228.aspx,对于EF 4.x进行了讨论.
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");
}
Run Code Online (Sandbox Code Playgroud)
...但是在EF 5.0(RC)上,这似乎不起作用,因为Refresh()我的EF5,代码优先,DbContext派生context类上不存在.
我确实看到了context.Entry(context.SalesOrderHeaders).Reload();- 但这似乎是一个直接从db重新加载而不是刷新/合并(与策略客户端获胜).
任何想法如何处理EF5中的乐观并发异常?实际上甚至在SaveChanges()中关于异常处理的一般指针都会很好
谢谢
Lad*_*nka 29
在DbContext API中如何解决并发异常的方法重新加载原始实体:
catch (DbUpdateConcurrencyException ex)
{
// Get failed entry
var entry = ex.Entries.Single(...);
// Overwrite original values with values from database but don't
// touch current values where changes are held
entry.OriginalValues.SetValues(entry.GetDatabaseValues());
}
Run Code Online (Sandbox Code Playgroud)
您还应该能够使用上面提到的代码,但是您必须ObjectContext从您的DbContext实例中获取实例(它只是一个包装器ObjectContext).
catch (DbUpdateConcurrencyException ex)
{
var objContext = ((IObjectContextAdapter)context).ObjectContext;
// Get failed entry
var entry = ex.Entries.Single(...);
// Now call refresh on ObjectContext
objContext.Refresh(RefreshMode.ClientWins, entry.Entity);
}
Run Code Online (Sandbox Code Playgroud)
你甚至可以尝试:
objContext.Refresh(RefreshMode.ClientWins, ex.Entries.Select(e => e.Entity));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17185 次 |
| 最近记录: |