views:

305

answers:

0

I'm trying to create an expression to be used by the Where method of a LINQ to Entities query.

Effectively:

query.Where(farm => farm.PartyId == id);

(id is an int)

The code I'm using is:

private struct Parameter<T>
{
    public T Value;

    public Parameter(T value)
    {
        Value = value;
    }

}

Parameter<int> idParameter = new Parameter<int>(id);
Expression<Func<FarmInfo, bool>> idExpression = Expression.Lambda<Func<FarmInfo, bool>>(Expression.Equal(
    Expression.Property(farmParameter, "PartyId"),
    Expression.Field(Expression.Constant(idParameter), "Value")), farmParameter);
expression = Expression.Lambda<Func<FarmInfo, bool>>(Expression.OrElse(textExpression.Body, idExpression.Body), farmParameter);

This produces the an SQL statement where "id" is replaced with "@p__linq__6" which is what I want because it will allow the SQL execution plan to be reused later. However, having to create the Parameter struct is an ugly hack. If I remove it and just use an Expression.Constant(id) instead, the SQL statement ends up putting the actual value of "id" (e.g. 42) directly into the statement rather than using a parameter.

There must be a better way to keep "id" parameterized in the SQL statement than the way I'm doing it. What is it?