views:

141

answers:

1

This is the code I need to alter:

var xParam = Expression.Parameter(typeof(E), typeof(E).Name);
MemberExpression leftExpr = MemberExpression.Property(xParam, this._KeyProperty);
Expression rightExpr = Expression.Constant(id);
BinaryExpression binaryExpr = MemberExpression.Equal(leftExpr, rightExpr);
//Create Lambda Expression for the selection
Expression<Func<E, bool>> lambdaExpr = Expression.Lambda<Func<E, bool>>(binaryExpr, new ParameterExpression[] { xParam });

Right now the expression I'm getting out of this is (x => x.RowId == id) and what I want to change it to is (x => x.RowId) so that I can use it in an OrderBy for the ObjectContext.CreateQuery(T) method called later on.

Does anyone know how to change the above code so the lambda is correct to use in an OrderBy to order by the ID field?

Side Notes: The RowId is coming from this._KeyProperty I believe. This is part of a generic repository using the entity framework on Asp.Net MVC

+3  A: 

Just omit creating the constant and "=":

  var xParam = Expression.Parameter(typeof(E), "x");
  var propertyAccessExpr = Expression.Property(xParam, this._KeyProperty);
  var lambdaExpr = Expression.Lambda<Func<E, bool>>(propertyAccessExpr, xParam);

This assumes that _KeyProperty has type 'bool'. If it has a different type, just change Func<E, bool> to the appropriate type.

(Edited to incorporate asgerhallas and LukLed's good suggestions)

Ray Burns
I believe it should be a Func<E, int> or something like that then.
asgerhallas
Or more precisely the type of the key property...
asgerhallas
Thanks for pointing that out. I updated the answer.
Ray Burns
I think that you can change var lambdaExpr = Expression.Lambda<Func<E, bool>>(propertyAccessExpr, new ParameterExpression[] { xParam }) to var lambdaExpr = Expression.Lambda<Func<E, bool>>(propertyAccessExpr, xParam); You don't have to create ParameterExpression array.
LukLed
Worked perfectly, thanks!
Matt
@LukLed You are correct. The original code had the "new ParameterExpression[]" and I just left it. I'll update the answer. Thanks.
Ray Burns