Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get original values of an entity in Entity Framework?

Tags:

In EF 4.0, if I understand it right, there are two type of values in Entity : current values and original values.
We can set original values by calling ApplyOriginalValues(TEntity) method but how to get original values ?

like image 474
JatSing Avatar asked Nov 15 '11 09:11

JatSing


People also ask

How do I get original entity from ChangeTracker?

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.

What is DbEntityEntry?

The DbEntityEntry enables you to access the entity state, and current and original values of all properties of a given entity. The following example code shows how to retrieve important information of a particular entity.

How do I use Find in entity Framework?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.


2 Answers

@Eranga answer is outdated for EF 5. For some reason, EF 5 doesn't work fine when getting original values using an statement like this:

var originalValues = context.Entry(myEntity).OriginalValues;

My working solution uses AsNoTracking() method from DbSet, like the example below:

var originalEntity = context.MyEntities.AsNoTracking().FirstOrDefault(me => me.MyEntityID == myEntity.MyEntityID);
like image 195
Leonel Sanches da Silva Avatar answered Oct 22 '22 02:10

Leonel Sanches da Silva


You can access them through ObjectStateEntry

var originalValues = context
         .ObjectStateManager.GetObjectStateEntry(myEntity).OriginalValues;
like image 28
Eranga Avatar answered Oct 22 '22 01:10

Eranga