使用entity的属性创建表达式树(Expression <func <tentity,bool =“”>&gt;)(x.ID == 123)</func <tentity,>

时间:2014-03-18 09:19:00

标签: c# lambda expression-trees

我使用泛型函数模式,参数为TEntity 例如,TEntity是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; }
} 

我需要生成一个表达式树,如下所示(自动):

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

用于以下方法的返回类型

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

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

根据您的说明/评论,以下内容适合您:

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