解决Expression<Func<T, bool>>表达式的AND和OR不能同时使用
public static Expression<Func<TableModel, bool>> GetExpressionOr(object objSearch, string typeName) { Expression<Func<TableModel, bool>> searchPredicate = PredicateExtensions.True<TableModel>(); if (objSearch != null) { //在这里编辑表达式 MySearch Serach = (MySearch)objSearch; switch (typeName) { case "SuitableIds": //搜索条件一 if (Serach.SuitableIds != null && Serach.SuitableIds.Count > 0) { string SuitableId = Serach.SuitableIds[0]; searchPredicate = searchPredicate.And(e => ("," + e.SuitableHumanIds + ",").Contains("," + SuitableId + ",")); for (int i = 1; i < Serach.SuitableIds.Count; i++) { string SuitableIdTemp = Serach.SuitableIds[i]; searchPredicate = searchPredicate.Or(e => ("," + e.SuitableHumanIds + ",").Contains("," + SuitableIdTemp + ",")); } } break; case "CategoryIds": //搜索条件二 if (Serach.CategoryIds != null && Serach.CategoryIds.Count > 0) { string CategoryId = Serach.CategoryIds[0]; searchPredicate = searchPredicate.And(e => ("," + e.CategoryIds + ",").Contains("," + CategoryId + ",")); for (int i = 1; i < Serach.CategoryIds.Count; i++) { string CategoryIdTemp = Serach.CategoryIds[i]; searchPredicate = searchPredicate.Or(e => ("," + e.CategoryIds + ",").Contains("," + CategoryIdTemp + ",")); } } break; case "MainIds": //搜索条件三 if (Serach.MainIds != null && Serach.MainIds.Count > 0) { string MainId = Serach.MainIds[0]; searchPredicate = searchPredicate.And(e => ("," + e.FoodIdList + ",").Contains("," + MainId + ",")); searchPredicate = searchPredicate.Or(e => ("," + e.AdjuvantList + ",").Contains("," + MainId + ",")); searchPredicate = searchPredicate.Or(e => ("," + e.SpiceList + ",").Contains("," + MainId + ",")); for (int i = 1; i < Serach.MainIds.Count; i++) { string MainIdTemp = Serach.MainIds[i]; searchPredicate = searchPredicate.Or(e => ("," + e.FoodIdList + ",").Contains("," + MainIdTemp + ",")); searchPredicate = searchPredicate.Or(e => ("," + e.AdjuvantList + ",").Contains("," + MainIdTemp + ",")); searchPredicate = searchPredicate.Or(e => ("," + e.SpiceList + ",").Contains("," + MainIdTemp + ",")); } } break; } } return searchPredicate; }
用多个where进行调用,调用方法:
using (FanacialDataContext context = new FanacialDataContext()) { //这里or语法和and语法必须要分开,一整个or用单独where查询,多个or用多个where,否则查询不正确 queryAble = context.vwContentCookList.Where(predicate).Where(CreatevwContentCookListExpression.GetExpressionOr(objSearch, "SuitableIds")).Where(CreatevwContentCookListExpression.GetExpressionOr(objSearch, "CategoryIds")).Where(CreatevwContentCookListExpression.GetExpressionOr(objSearch, "MainIds")); recordCount = queryAble.Count(); CreatevwContentCookListExpression.GetIQueryAble(ref queryAble, orderItem); result = queryAble.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); }

浙公网安备 33010602011771号