[英]Entity Framework (3.5) - Reject Changes
I have this service which is Singleton and Single threaded and serves bunch of low volume clients. 我有这个Singleton和Single线程的服务,并为一堆小批量客户端提供服务。 It uses Entity Framework and Data in SQL Server. 它在SQL Server中使用实体框架和数据。
If any one of the client's request to Save Data fails, all the subsequent requests are being failed as every time it is trying to save the original failed data object. 如果客户端的任何一个保存数据请求失败,则每次尝试保存原始失败数据对象时,所有后续请求都将失败。
Is there is any way to Undo changes to EF data when save fails? 保存失败时,是否有任何方法可以撤消对EF数据的更改?
Thanks in Advance 提前致谢
Entity-models / data-contexts / etc are best handled as units of work. 实体模型/数据上下文/等最好作为工作单元处理。 If you need to cancel it, simply discard the context and start with a new one. 如果您需要取消它,只需丢弃上下文并从新的上下文开始。 And if you succeed, discard it anyway! 如果你成功了,无论如何都要丢弃它! Each request should really be using separate data-contexts, otherwise you can get a range of problems: 每个请求应该使用单独的数据上下文,否则您可能会遇到一系列问题:
Note: you can upgrade to EF 4.1 or 4.2 which makes this job easy as a charm: 注意:您可以升级到EF 4.1或4.2,这使得这项工作变得简单:
context.Entry(myEntity).State = EntityState.Unchanged;
Please refer to this for detail. 请参考此查看详细。
Create a partial class to your ObjectContext
generated class, and include the following methods in it (VB, sorry - should be easily transcribed to C#): 为ObjectContext
生成的类创建一个部分类,并在其中包含以下方法(VB,抱歉 - 应该很容易转录为C#):
Public ReadOnly Property DirtyObjects() As IEnumerable(Of ObjectStateEntry)
Get
Return ObjectStateManager.GetObjectStateEntries(
EntityState.Added Or
EntityState.Deleted Or
EntityState.Modified)
End Get
End Property
Public Overloads Sub Refresh()
For Each entry In DirtyObjects
Select Case entry.State
Case EntityState.Modified
Dim original = entry.OriginalValues
For Each prop In entry.GetModifiedProperties()
Dim ordinal = original.GetOrdinal(prop)
entry.CurrentValues.SetValue(ordinal, original(ordinal))
RaisePropertyChanged(entry.Entity, prop)
Next
entry.AcceptChanges()
Case EntityState.Deleted
'I think I would need to call the above again, cuz it might be
'changed values on a Deleted-state entry too.
entry.ChangeState(EntityState.Unchanged)
Case EntityState.Added
entry.ChangeState(EntityState.Detached)
Case Else
'do nothing
Debug.Fail("It's not supposed to stop here.")
End Select
Next
End Sub
Heads up! 小心! In the new upcoming version this feature has became hell of a lot easier. 在即将推出的新版本中,这个功能变得更加容易。
问题的答案是“你不能放弃对上下文的更改”,而是必须丢弃ObjectContext,正如Marc解释的那样。
You can refresh the entity by calling 您可以通过调用刷新实体
context.Refresh(RefreshMode.StoreWins, entity)
so I see no need for RejectChanges. 所以我认为不需要RejectChanges。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.