首页 > 代码库 > 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操作符 (修订版)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。