EF中扩展出Between操作符 (修订版)
随手记录一下,这是针对原文错误的修改。
直接使用是错误的,修改后的扩展方法:
/// <summary> /// 扩展 Between 操作符 /// 使用 var query = db.People.Between(person => person.Age, 18, 21); /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="source"></param> /// <param name="keySelector"></param> /// <param name="low"></param> /// <param name="high"></param> /// <returns></returns> public static IQueryable<TSource> Between<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, TKey low, TKey high) where TKey : IComparable<TKey> { Expression key = Expression.Invoke(keySelector, keySelector.Parameters.ToArray()); Expression lowerBound = Expression.GreaterThanOrEqual(key, Expression.Constant(low)); Expression upperBound = Expression.LessThanOrEqual(key, Expression.Constant(high)); Expression and = Expression.AndAlso(lowerBound, upperBound); Expression<Func<TSource, bool>> lambda = Expression.Lambda<Func<TSource, bool>>(and, keySelector.Parameters); return source.Where(lambda.Compile()).AsQueryable(); }
作者:愤怒的TryCatch
请尊重别人的劳动成果,让分享成为一种美德,欢迎转载。另外,文章在表述和代码方面如有不妥之处,欢迎批评指正。留下你的脚印,欢迎评论!