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

StackOverflow https://stackoverflow.com/questions/22474913

  •  16-06-2023
  •  | 
  •  

Question

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 ?

Was it helpful?

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);
}

OTHER TIPS

    public List<Expression<Func<TEntity, bool>>> Filters { get; set; } = new List<Expression<Func<TEntity, bool>>>();

implement IQueryable

    if (xxx.Filters != null && xxx.Filters.Any())
    {
        foreach (var filter in xxx.Filters)
        {
            list = list.Where(filter);
        }
    }

set filters

    xxx.Filters.Add(x => x.YourProperty1Name.Contains("98"));
    xxx.Filters.Add(x => x.YourProperty2Name.Equals("abc"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top