如何使用NHibernate实现ChangeTime和ChangeUser列? [英] How do I implement ChangeTime and ChangeUser columns using NHibernate?

查看:62
本文介绍了如何使用NHibernate实现ChangeTime和ChangeUser列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将NHibernate与现有数据库一起使用.在数据模型中,每个表中都有一列,其中包含对行进行的最后更新的时间和用户名.如何使用NHibernate做到这一点?

I'm trying to use NHibernate with an existing database. In the data-model there is columns in each table that contains the time and username of the last update made to a row. How do I do this using NHibernate?

我尝试实现一个拦截器,该拦截器在使用IInterceptor.OnSave方法保存之前在实体中设置ChangeTime和ChangeUser.这是行不通的,因为即使没有其他属性被修改,设置这些属性也会触发该行的更新.

I tried to implement a interceptor that sets ChangeTime and ChangeUser in the entities before it gets saved using the IInterceptor.OnSave method. This didn't work because setting these properties triggers an update to the row even if no other properties has been modified.

如果有任何方法告诉NHibernate排除ChangeTime和ChangeUser属性,则它可能会起作用,然后进行脏检查.但是我还没有找到任何方法来实现这一目标.

It could have worked if there was any way to tell NHibernate to exclude the ChangeTime and ChangeUser properties then it does it's dirty-checking. But i haven't found any way to accomplish this.

感谢您的帮助.

推荐答案

您应该为预插入和预更新事件注册一个侦听器.您可以像这样通过配置来完成它:

You should register a listener to the pre insert and pre update events. You can do it through your configuration like so:

<hibernate-configuration>
    ...
    <event type="pre-update">
        <listener class="MyListener, MyAssembly"/>
    </event>
    <event type="pre-insert">
        <listener class="MyListener, MyAssembly"/>
    </event>
</hibernate-configuration>

然后实现一个侦听器-像这样(可能不完全准确-记下我的记忆):

and then implement a listener - something like this (might not be entirely accurate - written off my memory):

public class MyListener : IPreUpdateEventListener, IPreInsertEventListener
{
    public bool OnPreUpdate(PreUpdateEvent evt)
    {
        if (evt.Entity is IHasLastModified)
            UpdateLastModified(evt.State, evt.Persister.PropertyNames);

        return false;
    }

    public bool OnPreInsert(PreInsertEvent evt)
    {
        if (evt.Entity is IHasLastModified)
            UpdateLastModified(evt.State, evt.Persister.PropertyNames);

        return false;
    }

    void UpdateLastModified(object[] state, string[] names)
    {
        var index = Array.FindIndex(names, n => n == "LastModified");

        state[index] = DateTime.Now;
    }
}

并对更新前事件执行相同的操作.

and do the same thing with the pre update event.

这一步既要处理插入又要进行更新,并且似乎可以正常工作.

This one takes care of insert as well as update and it seems to work.

这篇关于如何使用NHibernate实现ChangeTime和ChangeUser列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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