码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-09-09 13:37:42      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

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

原文: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操作符 (修订版)

标签:

原文地址:http://www.cnblogs.com/likeli/p/5856211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!