Building Predicate in LINQ or Entity Framework

From Logic Wiki
Jump to: navigation, search

BuildLinqExpressionsDynacallyExpression.png

  • ParameterExpression (x): This is the parameter which is passed to the body
  • MemberExpression (x.Id): This is a property or field of the parameter type
  • ConstantExpression (3): This is a constant value

A nd to build an expression like this one, we would need a code like this:

using System.Linq.Expressions;

var parameter = Expression.Parameter(typeof(Person), "x");
var member = Expression.Property(parameter, "Id"); //x.Id
var constant = Expression.Constant(3);
var body = Expression.GreaterThanOrEqual(member, constant); //x.Id >= 3
var finalExpression = Expression.Lambda<Func<Person, bool>>(body, param); //x => x.Id >= 3


See : Build Lambda Expressions Dynamically