修改MethodCallExpression参数(C#LINQ)

时间:2017-05-15 11:48:52

标签: linq nhibernate odata

我需要在为{GET请求执行

之前为MethodCallExpression添加参数

这是加载所有员工的OData GET请求:

server/employees?$filter=birthday+ge+datetime'1985-01-01'

我尝试使用以下代码:

// My class inherits from IQToolkit which is building an expression based on the request
public class MyQueryProvider : QueryProvider 
{
    // Is defined in advance (after a client established a connection)
    private int clientDepartmentNo;

    // This is the central function, which gets a MethodCallExpression from the toolkit 
    // and executes it
    public override object Execute(MethodCallExpression expression)
    {
        // The current content of expression (see my OData URL above):
        // "value(NHibernate.Linq.NhQueryable`1[Models.Employee]).Where(it => (it.Birthday >= Convert(01.01.1985 00:00:00)))"

        // Now I would like to extend the expression like that:
        // "value(NHibernate.Linq.NhQueryable`1[Models.Employee]).Where(it => (it.Birthday >= Convert(01.01.1985 00:00:00)) && it.DepartmentNo == clientDepartmentNo)"

        // That works fine
        var additionalExpressionArgument = (Expression<Func<Employee, bool>>)(x => x.DepartmentNo == clientDepartmentNo);


        // But that is still not possible, because the property .Arguments is readonly...
        expression.Arguments.Add(additionalExpressionArgument);
        // Can you give me an advice for a working solution?


        // Would like to execute the query based on the URL and extension
        return nHibernateQueryProvider.Execute(expression);
    }
}

我应该怎样做以代替上面的expression.Arguments.Add

1 个答案:

答案 0 :(得分:2)

猜测您的QueryProvider是来自here的那个,并且在您的问题中对查询实体进行硬编码适合您,它应该很简单:

public override object Execute(MethodCallExpression expression)
{
    var query = (Query<Employee>)(CreateQuery<Employee>(expression)
        .Where(x => x.DepartmentNo == clientDepartmentNo));

    return nHibernateQueryProvider.Execute(query.Expression);
}

但是可能有更好的方法来做到这一点,因为该工具包用于构建表达式。像我上面那样进行硬拼接看起来像代码味道。