1

I have two entities: Product and StockItem.
When I insert a product - I have to update the relevant StockItem.
When I delete a product - I have to update the relevant StockItem as well.

My problem is updating the stock item in case of product update (modification). In order to update the relevant StockItem, I need to know if a field named Group in the Product entity has changed. To do so I have to compare between the modified version of the entity and the unmodified version of the entity. But whenever I ask for the entity - the entity framework returns the attached entity (and not the old one from the database).

How can I ask the entity framework to return the old version / current db version of the entity (before change)?

Naor
  • 21,508
  • 42
  • 135
  • 250

1 Answers1

3

What you see is result of identity map pattern used by ORM tools. Every entity with unique entity key can be attached to the context only once = you will never have two versions of the entity with the same entity key loaded twice to the same context.

By default EF always returns already loaded instance if your query returns record with the same entity key. This behaviour can be changed but still you will have only single instance of the entity.

Did you load the entity from EF with the same context instance as you are going to use for saving? If yes you already have old values. Use:

ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(yourEntity);
int someIntProperty = (int)entry.OriginalValues["SomeIntProperty"];

If you didn't load entity from the same context you can still use this approach but before that you must force EF to reload original values:

objectContext.YourEntitySet.MergeOption = MergeOption.PreserveChanges;
YourEntity entity = objectContext.YourEntitySet.Single(e => e.Id == entityId);

Now the OriginalValues collection in entry will be populated from database.

Another solution is simply using two different contexts - one for current entity state and one for old entity state.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654