先写一个拓展方法

static class Ext
{
   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);
   }
}

调用

var query = db.People.Between(person => person.Age, 18, 21);

 

相关文章:

  • 2021-11-28
  • 2022-12-23
  • 2019-09-25
  • 2022-12-23
  • 2021-05-29
  • 2021-08-01
  • 2022-01-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-30
相关资源
相似解决方案