设有对象:
class Student
{
pubic string Name{get;set;}
}
查询时,使用t=>t.Name=="jim";但如果条件参数不是固定的,需要动态构造,则不能在代码中这样硬编码了,需要使用Expression动态创建。如下所示:
Expression<Func<Student, bool>> Build(Student student)
{
var pe = Expression.Parameter(typeof(Student));
var p=typeof(TModel).GetProperty("Name");
var memberExpression = Expression.PropertyOrField(pe, p.Name);
var equalExpression = Expression.Equal(memberExpression, Expression.Constant(p.GetValue(student,null));
return Expression.Lambda<Func<Student, bool>>(equalExpression, pe));
}