EF CodeFirst 不得不说的Where与OrderBy
先来聊上5毛钱的“排序”
Code:
using (ApplicationDbContext Db=new ApplicationDbContext())
{
var res = Db.Threes.OrderBy(t => t.Id);
}
So Easy。现实往往不是这样的,有时我们需要让它灵活一点,如下这样方在一个函数里
Code:
public List<ApplicationDbContext.Three> GetAll()
{
using (ApplicationDbContext Db = new ApplicationDbContext())
{
return Db.Threes.OrderBy(t => t.Id).ToList();
}
}
显然这个代码是不灵活的,如果我们不想按照ID排序了,再去写一个方法就不好了。为了灵活我们可以把排序写在外面,在里面调用。怎样才能在方法里执行外面的排序?委托就可以
Code:
public ActionResult Index()
{
GetAll(db => db.OrderBy(t => t.Id));//注释1:随意设置排序字段
return View();
}
public IOrderedQueryable<ApplicationDbContext.Three> GetAll(Func<IQueryable<ApplicationDbContext.Three>,IOrderedQueryable<ApplicationDbContext.Three>> order)
{
using (ApplicationDbContext Db = new ApplicationDbContext())
{
var data = Db.Threes.Select(t => new ApplicationDbContext.Three { Id = t.Id });
return order(data);
}
}
在注释1的地方OrderBy里的表达式就可以改变排序的字段。这样就比灵活了许多。这样还是不够灵活,很多情况下我们的排序字段是前端传过来的。IQueryable的扩转方法OrderBy接受一个表达式类型的参数,我们可以把前端传过来的值生成一个表达式
Code:
生成表达式
private static LambdaExpression GetLambdaExpression<T>(string propertyName)
{
ParameterExpression parameter = Expression.Parameter(typeof(T));
MemberExpression body = Expression.Property(parameter, propertyName);
return Expression.Lambda(body, parameter);
}
排序方法
public static IOrderedQueryable<T> OrderBy<T>(IQueryable<T> source, string propertyName)
{
dynamic orderByExpression = GetLambdaExpression<ApplicationDbContext.Three>(propertyName);
return Queryable.OrderBy(source, orderByExpression);
}
使用例子
public ActionResult Index()
{
GetAll("Id");
return View();
}
public List<ApplicationDbContext.Three> GetAll(string orderByName)
{
using (ApplicationDbContext Db = new ApplicationDbContext())
{
var data = Db.Threes.Where(t => t.Id > 0);
return OrderBy(data,orderByName).ToList();}
}
}
在排序方法里我们调用了生成表达式方法,把结果返回给动态类型变量,这样做是为了解决类型不对应的问题。最后调用Queryable.OrderBy方法把数据以及表达式作为参数。为了使用方便,我们把OrderBy方法改成扩展方法,加个this就可以了。
排序方法
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
dynamic orderByExpression = GetLambdaExpression<ApplicationDbContext.Three>(propertyName);
return Queryable.OrderBy(source, orderByExpression);
}
使用例子
using (ApplicationDbContext Db = new ApplicationDbContext())
{
var data = Db.Threes.OrderBy1("Id").ToList();
}
是不是简单了很多。
再来聊聊“Where”
Code:
using (ApplicationDbContext Db = new ApplicationDbContext())
{
Db.Threes.Where(t => t.Id == 1);
}
这样写如果我们想要再加一个条件该怎么办呢。
Db.Threes.Where(t => t.Id == 1).Where(t => t.Text == "");
这样连续的Where都是“and”如果想要“or”该怎么办呢,还是要依赖于表达式
Code:
生成表达式
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
var ExBody = Expression.Or(expr1.Body, invokedExpr);
return Expression.Lambda<Func<T, bool>>
(ExBody, expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}
}
使用例子
var predicate = PredicateBuilder.False<ApplicationDbContext.Three>();
predicate = predicate.Or(p => p.Text== "2");
redicate = predicate.Or(p => p.Text == "1");
var func = predicate.Compile();//注释一
using (ApplicationDbContext Db = new ApplicationDbContext())
{
Db.Threes.Where(func);
}
这就就可以收索出Text是“2”或者是“1”的数据了。其实这样有一个问题,看注释一,这是把表达式生成委托传递进去的,所以是把全部数据加载到内存后筛选结果的。那如何才能不加载全部数据呢,请看下面。
Code:
从新绑定参数
public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
生成表达式
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.And);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.Or);
}
}
使用例子
var predicate = PredicateBuilder.False<ApplicationDbContext.Three>();
predicate = predicate.Or(p => p.Text != "2");
using (ApplicationDbContext Db = new ApplicationDbContext())
{
Db.Threes.Where(predicate);
}
此方法和上面的方法关键都是替换表达的参数,保证每一个表达式的参数都是同一个。
上面的方法是采用Expression.Invoke实现统一参数的,因为使用了Expression.Invoke,所以要编译成可执行代码,转换成委托,这样就要先全部加载数据到内存后处理了。现在的方法是采用重写ExpressionVisitor里的VisitParameter方法来实现参数统一的。
这样就实现了我们先要的,可是很多情况下,查询条件也是从前端传递过来的。那我们如何实现这样的需求呢。上神器:Linq 动态查询库,System.Linq.Dynamic
URL:http://dynamiclinq.codeplex.com/documentation
Code:
使用例子
using (ApplicationDbContext Db = new ApplicationDbContext())
{
var lala = Db.Threes.Where("Id!=2").OrderBy("Id");
}
不单单支持Where、OrderBy还有GroupBy、Selec、Ski、Take、Union等扩展方法
是不是很爽,是不是恨我没有一开始就写这个。
2016年:让我们更努力一点,梦想更靠近一点,把时间更多的浪费在美好的事物上面。