开发者

When to use ApplyOriginalValues in Entity Framework 4?

I have used ApplyCurrentValues.

But don't really understand ApplyOriginalValues. How is it different from ApplyCurrentValues? When should I use it?

I have read开发者_运维知识库 the documentation. But still confused.


Each entity loaded from the database keeps two sets of values - original (those loaded form DB) and current (those you are modifying). These two sets are hold in ObjectStateEntry. Usually each save is followed by accepting changes which takes current values and writes them to original values. If you know that you made changes to the entity outside of EF (for example by calling stored procedure with common ADO.NET EF) you can force EF to know about those changes without reloading the entity by using ApplyOriginalValues. I think using this method is rather rare. For example I used ApplyOriginalValues in this answer.


Calling either method seems to depend on whether the original entity or updated entity was attached. http://msdn.microsoft.com/en-us/library/bb896248.aspx


I just recently used the ApplyOriginalValues() method for use in a soft delete, or logical delete scenario.

We are using Entity Framework 4.1 and have implemented logical/soft deletes when the context saves changes.

The code below checks to see if the entity is deleted, then checks to see if it implements the proper interface. If so, we change the entity state from deleted to modified and apply the original values (entry.ApplyOriginalValues()), and set the deleted flag.

if (entry.State == EntityState.Deleted)
                {
                    if (entry.Entity is IEnforceLogicalDelete)
                    {
                        IEnforceLogicalDelete delete = entry.Entity as IEnforceLogicalDelete;
                        ObjectStateManager.ChangeObjectState(entry.Entity, EntityState.Modified);
                        entry.ApplyOriginalValues(entry.Entity);
                        delete.IsDeleted = true;
                    }
                }

Originally we had a problem where the Navigation Properties were getting set to NULL or empty when logically deleting. The ObjectContext.DeleteObject() method was flagging all the navigation properties for deletion before the Context.SavingChanges() event was triggered. When changing the state from deleted to modified, the foreign key properties were still wiped. I was trying to find a hook for the RevertDelete() method (ILSpy is very useful), but ApplyOriginalValues() worked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜