Modify MethodCallExpression Arguments (C # LINQ)

I need to add arguments to MethodCallExpression

before it gets executed for a GET request

This is an OData GET request to download all employees:

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

      

I've tried with the following code:

// 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);
    }
}

      

What should I do instead of the expression.Arguments.Add

above?

+3


source to share


1 answer


Assuming yours QueryProvider

is the one from here , and that hardcoding the requested object as in your question is fine for you, it should be simple:

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

    return nHibernateQueryProvider.Execute(query.Expression);
}

      



But there are probably better ways to do this, as this toolkit is here for building an expression. Forcing as I do above looks like a code smell.

+2


source







All Articles