【问题标题】:Write an insert or update and auditing Entity changes?How can I do it?编写插入或更新和审计实体更改?我该怎么做?
【发布时间】:2010-12-02 21:47:38
【问题描述】:

插入/更新实体时,我需要记录所有已更改的属性。 让我们拿两张表客户和地址。一个客户可以有多个地址。

任务:

将所有已更改的属性写入审计表?

如果你愿意,写一个更新方法的方法是什么。

我看到您可以使用以下内容:

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

【问题讨论】:

    标签: entity-framework entity-framework-4


    【解决方案1】:

    看看this post处理SavingChanges event
    您可以检查此事件中正在更新的对象的所有属性,并使用您的自定义代码记录它们。

    【讨论】:

    • 感谢您的回复和链接。看起来仍然不确定我如何将它们粘合在一起。我的意思是我有一个 customerDto 并且需要与现有客户进行比较并将更改写入日志表。任何更多指针?
    • 使用 OnPropertyChanged 事件创建已更改属性的列表,然后在 OnSavingChanges 事件中执行日志记录。更多关于 OnPropertyChanged:msdn.microsoft.com/en-us/library/cc716747.aspx
    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2014-12-08
    相关资源
    最近更新 更多