使用自定义hql生成器扩展linq-to-nhibernate

时间:2013-01-29 07:56:29

标签: c# nhibernate linq-to-nhibernate

目标是使用NHibernate和Linq做这样的事情:

Session.Query<MyClass>().Where(x => x.DateGreaterThen(DateTime.Now))

这个例子有点简化,但想法是在Where谓词中我想调用MyClass方法。所以MyClass看起来像:

public class MyClass
{
    public static readonly Expression<Func<MyClass, DateTime, bool>> GreaterThenExpression =
        (x, dt) => x.MyDateTimeProperty > dt.Date;

    private static readonly Func<MyClass, DateTime, bool> GreaterThenFunc = GreaterThenExpression.Compile();

    public Guid Id { get; set; }

    public DateTime MyDateTimeProperty { get; set; }

    public bool DateGreaterThen(DateTime dt)
    {
        return GreaterThenFunc(this, dt);
    }
}

自定义生成器:

public class EntityMethodGenerator<T1, T2, TResult> : BaseHqlGeneratorForMethod
{
    private Expression<Func<T1, T2, TResult>>  _returnValueExpression;

    public EntityMethodGenerator()
    {
        SupportedMethods = new[]
                               {
                                   ReflectionHelper.GetMethodDefinition<MyClass>(myClass => myClass.DateGreaterThen(DateTime.Now))
                               };
    }

    public static void Register(ILinqToHqlGeneratorsRegistry registry, Expression<Action<T1>> method, Expression<Func<T1, T2, TResult>> returnValueExpression)
    {
        var generator = new EntityMethodGenerator<T1, T2, TResult> { _returnValueExpression = returnValueExpression };

        registry.RegisterGenerator(ReflectionHelper.GetMethodDefinition(method), generator);
    }

    public override HqlTreeNode BuildHql(
        MethodInfo method,
        Expression targetObject,
        ReadOnlyCollection<Expression> arguments,
        HqlTreeBuilder treeBuilder,
        IHqlExpressionVisitor visitor)
    {
        return visitor.Visit(_returnValueExpression);
    }
}

最后自定义自定义生成器注册表:

public class OwnLinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
    public OwnLinqToHqlGeneratorsRegistry()
    {
        EntityMethodGenerator<MyClass, DateTime, bool>.Register(this, (myClass) => myClass.DateGreaterThen(DateTime.Now), MyClass.GreaterThenExpression);
    }   
}

但这不起作用,我得到System.Data.SqlClient.SqlException : Invalid column name 'dt'.我怀疑我的BuildHql方法没有正确实现,有任何帮助解决这个问题吗?

顺便说一句,我想在生成器中使用表达式,比如GreaterThenExpression,而不是在BuildHql方法中手动构建HqlTree

1 个答案:

答案 0 :(得分:1)

GreaterThenExpression是一个lamba。在BuildHql()中,您还需要注意targetObject和参数,否则您只是在HQL树中插入 unapplied lambda的一些HQL转换。

您需要提取lambda的主体并将其参数替换为targetObject和arguments。然后你可以从中生成HQL。尝试使用Remotion.Linq.Parsing.ExpressionTreeVisitors.MultiReplacingExpressionTreeVisitor。

(旁注,它应该是GreaterThan,而不是GreaterThen。)