开发者

Write an insert or update and auditing Entity changes?How can I do it?

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).Sing开发者_JS百科le();
        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();
     }
  }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜