简体   繁体   中英

Troubles creating a proper lambda expression

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM