首页 > 代码库 > EF中扩展出Between操作符 (修订版)

EF中扩展出Between操作符 (修订版)

随手记录一下,这是针对原文错误的修改。

原文: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();        }

 

EF中扩展出Between操作符 (修订版)