NHibernate Interceptor Auditing Inserted Object Id

后端 未结 2 1444
广开言路
广开言路 2021-01-01 01:57

I am using NHibernate interceptors to log information about Updates/Inserts/Deletes to my various entities.

Included in the information logged is the Entity Type and

相关标签:
2条回答
  • 2021-01-01 02:11

    try the OnFlushDirty method.. or maybe PostFlush

    edit: also, can you post your code? Don't you get the Id as a parameter to OnSave?

    0 讨论(0)
  • 2021-01-01 02:19

    I've worked around this problem by adding a list to my interceptor class which is populated with objects during the OnSave implementation.

    In the PostFlush implementation the list is iterated over and each element is audited as an insert. The objects in this list have been persisted in PostFlush() and thus have generated IDs.

    This seems to work OK but I'd be grateful if any potential pitfalls were pointed out :-)

    public class AuditInterceptor : EmptyInterceptor
    {       
        // To hold inserted items to be audited after insert has been flushed
        private IList<object> insertItems = new List<object>();
    
        public override void PostFlush(System.Collections.ICollection entities)
        {            
            foreach (var entity in insertItems)
            {
                AddAuditItem(entity, INSERT);
            }
            insertItems.Clear();
    
            base.PostFlush(entities);
        }
    
        public override bool OnSave(object entity, object id, object[] state, 
            string[] propertyNames, IType[] types)
        {            
            var auditable = entity as IAuditable;
            if (auditable != null) 
                insertItems.Add(entity);
    
            return false;            
        }
    }
    
    0 讨论(0)
提交回复
热议问题