开发者

Can I "undo" a LINQ to SQL update?

开发者 https://www.devze.com 2023-01-11 20:35 出处:网络
In LINQ-to-SQL if I update an object in the context but haven\'t called SubmitChanges, is there a way to \"undo\" or abandon that update so that the c开发者_运维问答hanges won\'t get submitted when I

In LINQ-to-SQL if I update an object in the context but haven't called SubmitChanges, is there a way to "undo" or abandon that update so that the c开发者_运维问答hanges won't get submitted when I eventually call SubmitChanges? For example, if I've updated several objects and then decide I want to abandon the changes to one of them before submitting.

Part 2: same question for Entity Framework, v3.5


Both LINQ to SQL and Entity Framework will use the same call (assuming you still have the active Context):

_dbContext.Refresh(RefreshMode.OverwriteCurrentValues, yourObj);

A more appropriate way would be to treat the Context as a Unit of Work, in which case you would no longer have an active context when refreshing the object. You would simply dispose of the object you're using currently and get a fresh copy from a new context.


I think you can use the .GetOriginalEntityState(yourEntity) to retrieve the original values. Then set your updated entity back to the original

dim db as new yourDataContext
//get entity
dim e1 as yourEntity = (from x in db.table1).take(1)
//update entity
e1.someProperty = 'New Value'
//get original entity
dim originalEntity = db.table1.getOrignalEntityState(e1)
e1 = originalEntity
db.submitChanges()

Very pseudo-code but I think it conveys the right idea. Using this method, you could also just undo one or more property changes without refreshing the entire entity.

0

精彩评论

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

关注公众号