在执EF多条件查询的时候,如果查询字段比较多、查询比较复杂需要动态的构建Expression条件,怎样将这些条件拼接在一起?
在论坛中查了一些关于《动态Lambda表达式》的例子,都比较复杂,有没有什么简便的方法?
望高手赐教!
比如下面的三个查询条件:
Expression<Func<Model.PM_PickStore, bool>> predicate1 = null;
if (PlanNo == "") { predicate1= o => o.DevID == 1; }
Expression<Func<Model.PM_PickStore, bool>> predicate2 = null;
if (PlanNo == "") { predicate2 = o => o.DevID == 2; }
Expression<Func<Model.PM_PickStore, bool>> predicate3 = null;
if (PlanNo == "") { predicate3 = o => o.DevID == 3; }
不是用linq吗.是要自己做表达式树解析?
转换下,大概如下:
var expression = Expression.Equal(Expression.Constant(1), Expression.Constant(1));
var parameterExpression = Expression.Parameter(typeof(Model.PM_PickStore), "p");
var propertyExpression = Expression.Property(parameterExpression, "DevID");
if (PlanNo == "") { expression = Expression.AndAlso(expression, Expression.Equal(propertyExpression, Expression.Constant(1)));}
if (PlanNo == "") { expression = Expression.AndAlso(expression, Expression.Equal(propertyExpression, Expression.Constant(2))); }
if (PlanNo == "") { expression = Expression.AndAlso(expression, Expression.Equal(propertyExpression, Expression.Constant(3))); }
谢谢您的赐教!
我在网上找了一个封装的方法,通过下面的代码可以实现了
var list = new List<Expression<Func<Model.PM_PickStore, bool>>>();
list.Add(o => true);
if (DevID != 0) list.Add(o => o.DevID == DevID);
if (StoreID != 0) list.Add(o => o.StoreID == StoreID);
if (PlanNo != "") list.Add(o => o.PlanNo.Equals(PlanNo));
Expression<Func<Model.PM_PickStore, bool>> productQueryTotal = null;
foreach (var expression in list)
{
productQueryTotal = expression.And(expression);
}
现在有个问题:进行模糊查询用什么方法,比如查PlanNo中含有“PL”字符的项
用Contains应该可以吧?