Search code examples
c#lambdaexpression-trees

Create expression tree (Expression<Func<TEntity, bool>>) with property of entity (x.ID == 123)


I use generic mode of function with a parameter as TEntity for example TEntity is Person

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string MobileNo { get; set; }
    public int Age { get; set; }
} 

I need generate an Expression Tree like the following (automaticaly):

Expression<Func<TEntity, bool>> :
          x=> x.ID = 123 && x.Name="AAA" && x.Family="BBB"

for return type of below method

public Expression<Func<TEntity, bool>> SearchExpression()
{
    HERE !!!
}

Can anyone help me for this purpose ?


Solution

  • Based on your description / comments, the following should work for you:

    public Expression<Func<TEntity, bool>> SearchExpression()
    {
        ConstantExpression[] expectedValues = Your_Magic_Method_Of_Obtaining_Expected_Values();
    
        var entity = Expression.Parameter(typeof (TEntity));
    
        var comparisonExpression = typeof(TEntity).GetProperties()
                                                  .Select((info, i) => Expression.Equal(
                                                                          Expression.Property(entity, info),
                                                                          expectedValues[i]))
                                                  .Aggregate(Expression.And);
        return Expression.Lambda<Func<TEntity, bool>>(comparisonExpression, entity);
    }