2

我已经设置了一个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 中)显示LastModification0001-01-01T00:00:00,如果我检查我在数据库中创建的实体,它也会显示相同的结果。

为什么这不起作用?

4

2 回答 2

2

您需要更改 currentState 值。首先在 propertyNames 中查找“LastModification”,如果找到则更改索引​​的 currentState。您也可以在 IType[] 中检查类型。

于 2013-09-04T16:53:22.113 回答
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;
    }
}

我的表达工具类:

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;
    }
}
于 2013-09-04T17:32:45.833 回答