Is there a way to get the original Entity itself from the ChangeTracker
(rather than just the original values)?
If the State
is Modified
, then I suppose I could do this:
// Get the DbEntityEntry from the DbContext.ChangeTracker...
// Store the current values
var currentValues = entry.CurrentValues.Clone();
// Set to the original values
entry.CurrentValues.SetValues(entry.OriginalValues.Clone());
// Now we have the original entity
Foo entity = (Foo)entry.Entity;
// Do something with it...
// Restore the current values
entry.CurrentValues.SetValues(currentValues);
But this doesn't seem very nice, and I'm sure there are problems with it that I don't know about... Is there a better way?
I'm using Entity Framework 6.
While working with EF 6 i used the following code to get the underlying POCO entity type from proxy type,
ObjectContext.GetObjectType
: Return the POCO from proxy objectNice. Here is a slightly modified version that will handle complex properties:
Override
SaveChanges
of DbContext or just accessChangeTracker
from the context:Here is a method which will create a new entity with the original values. Thus all entities should have a parameterless public constructor, you can simply construct an instance with
new
:I would suggest clone entities on materialization and attach them to second context to keep whole original objects graph (if you need it of course). You can make them all ICloneable by modifying T4 template.