Retrieving Initial Copies of Objects in a LINQ-to-SQL Changeset

When using LINQ-to-SQL, you can get a set of arrays of objects that will be updated, inserted, or deleted by calling DataContext.GetChangeSet()

. If there are conflicts, the property DataContext.ChangeConflicts

will give you references to the original and modified objects. Is there a way to access the original and modified objects if there is no conflict?

This should work for objects that don't implement INotifyPropertyChanging

/ INotifyPropertyChanged

.

+3


source to share


2 answers


var db = new DataContext();
db.GetChangeSet().Updates.ForEach(o => {
    var currentObject = o;
    var originalObject = db.GetTable(o.GetType()).GetOriginalEntityState(o);
    var changedProperties = db.GetTable(o.GetType()).GetModifiedMembers(o);
});

      



+3


source


I have not been able to find a way to do this through the public API. However, if you want to take your mind off reflection a bit (and preferably some compiled expressions to call and access any methods, constructors ), you can get the data.

Here's what you need to do:



  • Get a link to the private field of services

    your instance DataContext

    .
  • Create an instance System.Data.Linq.ChangeProcessor

    . This is the inner class that is actually used when you call DataContext.GetChangeset()

    . Pass the link to services

    from step 1 as well as the link to the instance DataContext

    .
  • Call a private and parameterless method GetOrderedList

    against your instance ChangeProcessor

    . This will give you List<TrackedObject>

    . Unfortunately, since TrackedObject

    it is also an inner class, you also need to use reflection to access its properties.
  • The objects we are looking for are in properties Current

    and Original

    instances TrackedObject

    . It also has some other useful properties, such as IsNew

    , IsModified

    and IsDeleted

    , which are perfectly understandable, and IsInteresting

    which I assume is any of the three previous properties being true.

Of course, since these are all internal APIs, they are subject to change when the framework is updated, so keep that in mind when using this logic.

0


source







All Articles