在使用EF使用Linq查询时,有些复杂的查询条件不能直接写Lambda表达式简单的拼装条件。
如 查询条件是有一组 like条件拼装,这时就要用到Expression表达式,下面直接上代码
public List<City> GetCitys(string[] areaCodes) { var type = typeof(City); var pe = Expression.Parameter(type); var property = type.GetProperty("AreaCode"); var leftProgramArea = Expression.Property(pe, property); var stringType = typeof(string); MethodInfo mi = stringType.GetMethod("StartsWith", new Type[] { typeof(string) }); List<MethodCallExpression> methodCalls = new List<MethodCallExpression>(); Expression<Func<City, bool>> whereLamda = null; foreach (var area in areaCodes) { var right = Expression.Constant(area, stringType); var call = Expression.Call(leftProgramArea, mi, right); methodCalls.Add(call); } if (methodCalls.Count == 1) { whereLamda = Expression.Lambda<Func<City, bool>>(methodCalls[0], pe); } else { if (methodCalls.Count > 1) { var be = Expression.Or(methodCalls[0], methodCalls[1]); for (var i = 2; i < methodCalls.Count; i++) { be = Expression.Or(be, methodCalls[i]); } whereLamda = Expression.Lambda<Func<City, bool>>(be, pe); } using (var ctx = new MyContext()) { return ctx.Citys.Where(whereLamda).ToList(); } } }
时间: 2024-10-27 11:56:26