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年:让我们更努力一点,梦想更靠近一点,把时间更多的浪费在美好的事物上面。

转载于:https://www.cnblogs.com/c-o-d-e/p/5205680.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Entity Framework Code First 可以方便地创建数据表。以下是基本步骤: 1.创建一个继承自 DbContext 的类,该类代表数据库上下文。 2.定义一个实体类,该类代表数据库中的一个表。在实体类上使用数据注解或 Fluent API,来指定表名、列名、数据类型、主键、外键等信息。 3.在数据库上下文类中,使用 DbSet 属性将实体类与数据库上下文关联起来。 4.创建一个数据库初始化类,该类继承自 DropCreateDatabaseIfModelChanges 或 CreateDatabaseIfNotExists,用于在应用程序启动时自动创建数据库和表。 5.在应用程序启动时,使用数据库初始化类的静态方法,来初始化数据库。 以下是一个示例: ```csharp // 1.创建数据库上下文 public class MyDbContext : DbContext { public DbSet<User> Users { get; set; } } // 2.定义实体类 public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } // 3.在数据库上下文中关联实体类 public class MyDbContext : DbContext { public DbSet<User> Users { get; set; } } // 4.创建数据库初始化类 public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyDbContext> { protected override void Seed(MyDbContext context) { // 初始化数据 context.Users.Add(new User { Name = "Tom", Age = 20 }); context.Users.Add(new User { Name = "Jerry", Age = 22 }); base.Seed(context); } } // 5.在应用程序启动时初始化数据库 Database.SetInitializer(new MyDbInitializer()); ``` 运行应用程序后,EF Code First 将会自动创建名为 MyDbContext 的数据库,并在其中创建一个名为 Users 的表,该表包含 Id、Name 和 Age 三列。同时,数据库初始化类 MyDbInitializer 会在数据库创建后,向 Users 表中插入两条初始化数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值