Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I "undo" a LINQ to SQL update?

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 changes 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

like image 938
Sisiutl Avatar asked Aug 12 '10 15:08

Sisiutl


2 Answers

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.

like image 72
Justin Niessner Avatar answered Sep 22 '22 04:09

Justin Niessner


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.

like image 32
Tommy Avatar answered Sep 21 '22 04:09

Tommy