2010-12-02 30 views
1

當插入/更新實體時,我需要記錄所有已更改的屬性。 讓我們拿2張客戶和地址。一個客戶可以有很多地址。編寫一個插入或更新和審計實體更改?我該怎麼做?

任務:

寫入審覈表的所有屬性已經改變?

是什麼,如果你喜歡,不只是要寫入的更新方法的方式。

我已經看到了你可以使用以下命令:

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

不知道你如何實際編寫方法雖然下面是一個半嘗試: 你能給我一些指點和幫助我的代碼?

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(); 
    } 
    } 

回答

1

看看this post處理SavingChanges event
您可以檢查此事件被更新的對象的所有屬性,並使用您的自定義代碼記錄他們。

+0

感謝您的回覆,並links.Looks promsing仍然不知道我怎麼把它粘所有together.I意味着我有一個customerDto,需要與現有的客戶比較和更改寫入日誌table.any更多的指針? – user9969 2010-12-02 14:42:53

相關問題