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

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I believe it should be a Func<E, int> or something like that then.
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 You are correct. The original code had the "new ParameterExpression[]" and I just left it. I'll update the answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.