0

My requirement is to update UpdatedDate property of the object whenever ObjectContext.SaveChanges method is called and for this I tried to attach event handler for savechanges event where I want to find the object that is being updated and update its UpdateDate property, but I am not finding the way to find the object that is getting updated.

Any idea? Am I doing the correct thing to achieve my requirement?

Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105

1 Answers1

0

you could look in the ObjectStateManager

something like this:

private void context_SavingChanges(object sender, EventArgs e)
{
    var context = (ObjectContext)sender;
    var lst = context.ObjectStateManager
                  .GetObjectStateEntries(EntityState.Modified); 

    foreach(var item in lst)
    { 
      var entity = item.Entity;
       // TODO: set values here:
    }  
}
Jens Kloster
  • 11,099
  • 5
  • 40
  • 54
  • Thanks a lot man! It worked greatly! Is there any predefined way like your answer to set the value of any of the property? Like I want to set the UpdatedDate value of the object being updated, or Reflection is the only way? – Pawan Nogariya Feb 18 '13 at 14:13
  • Np :) I would suggets you expand the entities that need to be updated with an interface (maybe `IUpdateEntity` or something) you can use in your loop. something like: `var entity = item.Entity as IUpdateEntity` – Jens Kloster Feb 18 '13 at 14:16
  • 1
    Yeah, that way came to my mind but fortunately reflection fulfilled the requirement more easily :) And now everything is working awesome! – Pawan Nogariya Feb 19 '13 at 06:55
  • I have posted one more question related to this here http://stackoverflow.com/questions/14952457/current-user-identity-in-objectcontext-savingchanges, if you have any answer for this – Pawan Nogariya Feb 19 '13 at 08:09