0

Referring - How to get original values of an entity in Entity Framework? - I tried to extract the original value(s) of an entity in EF. But the ObjectStateManager.GetOBjectStateEntry giving the modified value of the entity. What am I missing?

I am using EF 4.0 (POCO Entities) in a multi-layered environment.

    public bool Update(IMessage objMessage)
    {
        object ob = objMessage.GetMaster();
        appSancAdvice _entity = ob as appSancAdvice;

        using (var context = new BISEntities())
        {
            context.appSancAdvices.Attach(_entity);
            ObjectStateEntry objectState = context.ObjectStateManager.GetObjectStateEntry(_entity);
            objectState.ChangeState(System.Data.EntityState.Modified);

            // this is giving the modified value of _entity 
            var originalValues = context.ObjectStateManager.GetObjectStateEntry(_entity).OriginalValues["sancstatus_id"];

            int _i = context.SaveChanges();
            return (_i > 0) ? true : false;
        }
    }
Community
  • 1
  • 1
Khadim Ali
  • 2,548
  • 3
  • 33
  • 61

1 Answers1

0

The context does not know the original value because you attach the entity. If you want the original values, you must fetch the object from the database. It is not that EF does that automatically when you get OriginalValues from a newly attached object.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • Thanks Gert! So how about extending the entity in a partial class to add an object of same entity type that may hold retrieved entity's copy when required. Would it affect performance? – Khadim Ali Dec 17 '12 at 11:27
  • I would not do that. It makes your class doing things that is the context's responsibility. Keeping classes simple (single responsibility) is one of the core principles of OO design. If you want to compare/copy old and new values frequently, make a service class for it. – Gert Arnold Dec 17 '12 at 11:39
  • Gert! Would you please elaborate, how? A brief outline of such design. – Khadim Ali Dec 19 '12 at 08:58
  • I haven't got enough information for that, but it's also a new issue. I'd recommend you ask a new question with appropriate information, e.g. why you want this (auditing, reversing changes, ...?) and when/where. I'll see what I can do. – Gert Arnold Dec 19 '12 at 19:28
  • Just to update, I found this useful article on the web (but using self tracking entities). http://robbincremers.me/2012/02/01/entity-framework-using-self-tracking-entities-in-a-multi-layered-architecture/ – Khadim Ali Feb 07 '13 at 14:15