【问题标题】:Auditing to Ignore Certain Property Changes with NHibernate Event Listeners使用 NHibernate 事件侦听器审计以忽略某些属性更改
【发布时间】:2011-04-25 22:34:02
【问题描述】:

我已经在我的应用程序中连接了日志记录,以使用事件侦听器自动记录对某些实体的更改。这很好用,但是对于我正在记录的实体的某些属性,如果仅对该属性进行更改,我不希望插入日志。这些属性用 IgnoreLoggingAttribute 属性修饰。这是我到目前为止所拥有的:

public void OnPostUpdate(PostUpdateEvent @event)
{
    var session = @event.Session.GetSession(NHibernate.EntityMode.Poco);

    if (@event.Entity is User)
        session.SaveOrUpdate(new UserLog((User)@event.Entity));
    ...
}

@event 公开了 2 个属性,称为 State 和 OldState。我可以使用它来检查更改,但是我无法提取我感兴趣的属性,因为这些只是一个对象数组。我想我可以使用一些反射来获取所有索引(对于具有 IgnoreLoggingAttribute 的任何属性)并将它们与对象数组中的索引匹配。到目前为止,我想出了:

var properties = typeof(User).GetProperties().Where(p => p.GetCustomAttributes(typeof(IgnoreLoggingAttribute), false).Count() > 0);

现在的问题是它没有给我相对于原始实体的属性索引。我还需要确保这与 @event.State 和 @event.OldState 属性中的适当索引匹配(它们似乎都忽略了某些属性)。

【问题讨论】:

    标签: c# nhibernate event-listener


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      我可以通过在插入日志表之前调用这个方法来实现这一点:

      private bool IsDirty(PostUpdateEvent @event) {
          // Get all the mapped property names
          var propertyNames = @event.Session.Factory.GetClassMetadata(@event.Entity.GetType()).PropertyNames;
      
          // Get the property index to ignore
          var propertyIndexesToIgnore = @event.Entity.GetType().GetProperties()
              .Where(p => p.GetCustomAttributes(typeof(IgnoreLoggingAttribute), false).Count() > 0)
              .Select(p => Array.IndexOf(propertyNames, p.Name)).ToArray();
      
          if (@event.OldState != null && @event.State != null) {
              for (var i = 0; i < @event.OldState.Length; i++) {
                  if (!propertyIndexesToIgnore.Contains(i) && !@event.OldState[i].Equals(@event.State[i]))
                      return true;
              }
          }
      
          return false;
      }
      

      现在我要做的就是将 IgnoreLoggingAttribute 属性应用于我不想记录的任何属性。希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 2011-04-06
        • 1970-01-01
        • 2017-03-07
        • 2015-12-18
        • 1970-01-01
        相关资源
        最近更新 更多