利用EF和C#泛型实现通用分页查询

      Entity Framework 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (ORM) 解决方案,是微软的ORM框架。此框架将数据库中的表信息通过xml与实体类对象相关联,使得开发人员只需要关心实体对象,而不需要手动操作数据库,对实体对象的修改会映射到数据库中,这样大大提高了开发效率。以下代码使用了EF、泛型、泛型委托、lambda、匿名类、dynamic动态类型等知识完成了EF的crud,并且提供了一个高效的通用分页查询方法,采用了延时加载,返回值类型是IQueryable。
 using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text; namespace EFtest
{
class Program
{
static void Main(string[] args)
{
testEntities context = new testEntities(); //增
//T_Test t = new T_Test() {Name="小林" };
//context.T_Test.Add(t);
//context.SaveChanges(); //删
//lambda方式
//var t = context.T_Test.Where(u=>(u.Id==1)).FirstOrDefault(); //linq to sql方式
//var t = (from u in context.T_Test
// where u.Id == 1
// select u).FirstOrDefault();
//context.T_Test.Remove(t);
//context.SaveChanges();
//数据的删除用这种方式更方便,效率更高
//T_Test t = new T_Test() { Id=2 };
//context.Entry<T_Test>(t).State=EntityState.Deleted;
//context.SaveChanges(); //改
//var t = (from u in context.T_Test
// where u.Id == 2
// select u).FirstOrDefault();
//t.Name = "小林";
//context.SaveChanges(); //查
//var t = (from u in context.T_Test
// where u.Id == 2
// select u).FirstOrDefault();
//Console.WriteLine(t.Id + t.Name); //通用分页
int count;
GetPageListParameter<T_Test, int> parameter=new GetPageListParameter<T_Test,int>();
parameter.isAsc=true;
parameter.orderByLambda = s => s.Id;
parameter.pageIndex = ;
parameter.pageSize = ;
parameter.selectLambda = s => new Person{Name=s.Name };
parameter.whereLambda = s => s.Id > ; var data = GetPageList<T_Test, int>(parameter, out count); foreach (Person t in data)
{
Console.WriteLine(t.Name);
} Console.ReadKey();
} public static List<dynamic> GetPageList<T, TKey>(GetPageListParameter<T, TKey> parameter, out int count) where T : class
{
testEntities context = new testEntities();
//注意顺序
count = context.Set<T>().Where<T>(parameter.whereLambda).Count();
var list = context.Set<T>().Where<T>(parameter.whereLambda);
if (parameter.isAsc)
{
list = list.OrderBy(parameter.orderByLambda);
}
else
{
list = list.OrderByDescending(parameter.orderByLambda);
} return list.Skip((parameter.pageIndex - ) * parameter.pageSize).Take(parameter.pageSize).Select(parameter.selectLambda).ToList();
}
} //取所需列
public class Person
{
public string Name { get; set; }
} //封装方法参数
public class GetPageListParameter<T, TKey>
{
public Expression<Func<T, dynamic>> selectLambda { get; set; }
public Expression<Func<T, bool>> whereLambda { get; set; }
public Expression<Func<T, TKey>> orderByLambda { get; set; }
public int pageSize { get; set; }
public int pageIndex { get; set; }
public bool isAsc { get; set; }
}
}
05-11 11:17
查看更多