NHibernate Interceptor无法正常工作

时间:2013-09-04 16:21:50

标签: c# .net nhibernate

我已设置IIntercpetor来更新实体保存或更新时的时间戳(上次修改日期)。

我的实现如下:

public class NhInterceptor : EmptyInterceptor
{
    public override bool OnSave(object entity, object id, object[] state, 
        string[] propertyNames, NHibernate.Type.IType[] types)
    {
        var baseEntity = entity as EntityBase;
        if (baseEntity == null)
            return false;

        baseEntity.LastModification = DateTime.Now;
        return true;
    }

    public override bool OnFlushDirty(object entity, object id, 
        object[] currentState, object[] previousState, 
        string[] propertyNames, NHibernate.Type.IType[] types)
    {
        var baseEntity = entity as EntityBase;
        if (baseEntity == null)
            return false;

        baseEntity.LastModification = DateTime.Now;
        return true;
    }
}

此代码被点击,调试器在返回之前显示baseEntity.LastModification具有正确的值。

但是,我的Json输出(在Web API中)将LastModification显示为0001-01-01T00:00:00,如果我在数据库中检查我创建的实体,它也会显示相同的结果。

为什么这不起作用?

2 个答案:

答案 0 :(得分:2)

您需要更改currentState值。 首先在propertyNames中查找“LastModification”,然后在找到时更改索引的currentState。您也可以在IType []中查看类型。

答案 1 :(得分:1)

我决定根据Hylaean的回答为您提供我的工作解决方案。

我的拦截器类:

public class NhInterceptor : EmptyInterceptor
{
    public override bool OnSave(object entity, object id, object[] state, 
        string[] propertyNames, NHibernate.Type.IType[] types)
    {
        var baseEntity = entity as EntityBase;
        if (baseEntity == null)
            return false;

        var lastModificationPropName = ExpressionUtil
            .GetPropertyName<EntityBase>((e) => e.LastModification);

        for (int i = 0; i < propertyNames.Length; i++)
        {
            if (lastModificationPropName == propertyNames[i])
            {
                state[i] = DateTime.Now;
                return true;
            }
        }

        return true;
    }

    public override bool OnFlushDirty(object entity, object id, 
        object[] currentState, object[] previousState, 
        string[] propertyNames, NHibernate.Type.IType[] types)
    {
        var baseEntity = entity as EntityBase;
        if (baseEntity == null)
            return false;

        var lastModificationPropName = ExpressionUtil
            .GetPropertyName<EntityBase>((e) => e.LastModification);

        for (int i = 0; i < propertyNames.Length; i++)
        {
            if (lastModificationPropName == propertyNames[i])
            {
                currentState[i] = DateTime.Now;
                return true;
            }
        }
        return true;
    }
}

My Expression util class:

public static class ExpressionUtil
{
 public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
    {
        var body = expression.Body as MemberExpression;

        if (body == null)
        {
            body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
        }

        return body.Member.Name;
    }
}