开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜