Posted by: leppie | February 17, 2009

DataContext.RevertChanges()

Here is a nice extension method I dished up, to revert all changes in the DataContext. :)

(drop this in your DataContext partial class, or create a static/extension method for it)

public void RevertChanges()
{
  var cs = GetChangeSet();

  foreach (var item in cs.Inserts)
  {
    var t = item.GetType();
    GetTable(t).DeleteOnSubmit(item);
  }

  foreach (var item in cs.Deletes)
  {
    var t = item.GetType();
    GetTable(t).InsertOnSubmit(item);
  }

  foreach (var item in cs.Updates)
  {
    var t = item.GetType();
    foreach (var mm in GetTable(t).GetModifiedMembers(item))
    {
      var pi = mm.Member as PropertyInfo;
      if (pi != null)
      {
        pi.SetValue(item, mm.OriginalValue, null);
      }

      var fi = mm.Member as FieldInfo;
      if (fi != null)
      {
        fi.SetValue(item, mm.OriginalValue);
      }
    }
  }
#if DEBUG
  cs = GetChangeSet();
  Debug.Assert(cs.Deletes.Count == 0);
  Debug.Assert(cs.Inserts.Count == 0);
  Debug.Assert(cs.Updates.Count == 0);
#endif
}
About these ads

Responses

  1. GREAT method!
    Excelent work!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: