9

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

Sisiutl
  • 4,915
  • 8
  • 41
  • 54
  • possible duplicate of http://stackoverflow.com/questions/259219/how-can-i-reject-all-changes-in-a-linq-to-sqls-datacontext – relet Aug 12 '10 at 15:31
  • No, that article is about how to undo all the changes. I just want to abandon some of them. – Sisiutl Aug 12 '10 at 15:38

2 Answers2

3

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

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.

Tommy
  • 39,592
  • 10
  • 90
  • 121