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

查看:16
本文介绍了如何使用 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天全站免登陆