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

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

问题描述

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

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

记录的信息中包括实体类型和修改后的实体的唯一ID.唯一标识符在NHibernate映射文件中标记为<generator class="identity">.

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天全站免登陆