NHibernate 拦截器审计插入的对象 ID [英] NHibernate Interceptor Auditing Inserted Object Id

查看:31
本文介绍了NHibernate 拦截器审计插入的对象 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NHibernate 拦截器将有关更新/插入/删除的信息记录到我的各种实体中.

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

记录的信息中包括实体类型和修改实体的唯一 ID.在 NHibernate 映射文件中,唯一的 Id 被标记为 .

Included in the information logged is the Entity Type and the Unique Id of the entity modified. The unique Id is marked as a <generator class="identity"> in the NHibernate mapping file.

明显的问题是,当使用 IInterceptor.OnSave() 记录插入操作时,实体的 ID 尚未分配.

The obvious problem is when logging an Insert operation using IInterceptor.OnSave() the Id of the entity has not yet been assigned.

如何在记录审计信息之前获取插入实体的Id?

How can I obtain the Id of the inserted entity before logging the audit information?

(我已经研究了 NHibernate Listeners PostSave 事件,但无法让它们与正在使用的 Spring.net 配置一起工作,所以如果可能的话,我想坚持使用拦截器)

(I have looked into NHibernate Listeners PostSave event but can't get them working with the Spring.net configuration being used, so I would like to stick with interceptors if at all possible)

代码:

    // object id parameter is null...
    public override bool OnSave(object entity, object id, object[] state, 
        string[] propertyNames, IType[] types)
    {            
        AddAuditItem(entity, INSERT);
        return false;            
    }

推荐答案

我通过向拦截器类添加一个列表来解决这个问题,该列表在 OnSave 实现期间填充了对象.

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

PostFlush 实现中,列表被迭代并且每个元素都作为插入被审计.此列表中的对象已保存在 PostFlush() 中,因此生成了 ID.

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

这篇关于NHibernate 拦截器审计插入的对象 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆