1

When insert/updating an entity I need to log all the properties that have changed. Lets take 2 tables Customer and Address. A customer can have many addresses.

Task:

Write to the Audit Table all the properties that have changed?

what is the way to write an update method if you like that does just that.

I have seen that you can use the following:

  ObjectStateEntry entry = ObjectStateManager.GetObjectStateEntry(entity);
  var changes=  entry.GetModifiedProperties().

Not sure how you actually write the method though the following is an half attempt: can you give me few pointers or help me with the code?

  private  bool UpdateCustomer(Customer modifiedCustomerDto)
  {
     using (var ctx = new MyContext())
     {
        var oldCustomer = ctx.Customers.Where(xx => xx.CustomerId == modifiedCustomerDto.id).Single();
        oldCustomer.Name = modifiedCustomerDto.Name;
        oldCustomer.Surname = modifiedCustomerDto.Surname;

        foreach (var oldAddress in oldCustomer.Addresses)
        {
          //if it's a new Address add it 
           //else updateit
           //Write to the audit table all the properties that have changed.
        }

        //Get Modified properties and write to the auditlog

        ctx.SaveChanges();
     }
  }
user9969
  • 15,632
  • 39
  • 107
  • 175

1 Answers1

1

Take a look at this post dealing with the SavingChanges event.
You can check all properties of the object being updated in this event and log them using your custom code.

Community
  • 1
  • 1
Devart
  • 119,203
  • 23
  • 166
  • 186
  • thanks for your reply and links.Looks promsing still not sure how i glue it all together.I mean I Have a customerDto and need to compare with existing customer and write the changes to the log table.any more pointers? – user9969 Dec 02 '10 at 14:42
  • Use the OnPropertyChanged event to create a list of changed properties, and then perform logging in the OnSavingChanges event. More about OnPropertyChanged: http://msdn.microsoft.com/en-us/library/cc716747.aspx – Devart Dec 03 '10 at 16:08