利用EF和C#泛型实现通用分页查询
Entity Framework 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (ORM) 解决方案,是微软的ORM框架。此框架将数据库中的表信息通过xml与实体类对象相关联,使得开发人员只需要关心实体对象,而不需要手动操作数据库,对实体对象的修改会映射到数据库中,这样大大提高了开发效率。以下代码使用了EF、泛型、泛型委托、lambda、匿名类、dynamic动态类型等知识完成了EF的crud,并且提供了一个高效的通用分页查询方法,采用了延时加载,返回值类型是IQueryable。
1 using System; 2 using System.Collections.Generic; 3 using System.Data.Entity; 4 using System.Linq; 5 using System.Linq.Expressions; 6 using System.Text; 7 8 namespace EFtest 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 testEntities context = new testEntities(); 15 16 //增 17 //T_Test t = new T_Test() {Name="小林" }; 18 //context.T_Test.Add(t); 19 //context.SaveChanges(); 20 21 22 //删 23 //lambda方式 24 //var t = context.T_Test.Where(u=>(u.Id==1)).FirstOrDefault(); 25 26 //linq to sql方式 27 //var t = (from u in context.T_Test 28 // where u.Id == 1 29 // select u).FirstOrDefault(); 30 //context.T_Test.Remove(t); 31 //context.SaveChanges(); 32 //数据的删除用这种方式更方便,效率更高 33 //T_Test t = new T_Test() { Id=2 }; 34 //context.Entry(t).State=EntityState.Deleted; 35 //context.SaveChanges(); 36 37 //改 38 //var t = (from u in context.T_Test 39 // where u.Id == 2 40 // select u).FirstOrDefault(); 41 //t.Name = "小林"; 42 //context.SaveChanges(); 43 44 //查 45 //var t = (from u in context.T_Test 46 // where u.Id == 2 47 // select u).FirstOrDefault(); 48 //Console.WriteLine(t.Id + t.Name); 49 50 //通用分页 51 int count; 52 GetPageListParameter parameter=new GetPageListParameter (); 53 parameter.isAsc=true; 54 parameter.orderByLambda = s => s.Id; 55 parameter.pageIndex = 1; 56 parameter.pageSize = 3; 57 parameter.selectLambda = s => new Person{Name=s.Name }; 58 parameter.whereLambda = s => s.Id > 3; 59 60 var data = GetPageList (parameter, out count); 61 62 foreach (Person t in data) 63 { 64 Console.WriteLine(t.Name); 65 } 66 67 Console.ReadKey(); 68 } 69 70 public static List GetPageList (GetPageListParameter parameter, out int count) where T : class 71 { 72 testEntities context = new testEntities(); 73 //注意顺序 74 count = context.Set ().Where (parameter.whereLambda).Count(); 75 var list = context.Set ().Where (parameter.whereLambda); 76 if (parameter.isAsc) 77 { 78 list = list.OrderBy(parameter.orderByLambda); 79 } 80 else 81 { 82 list = list.OrderByDescending(parameter.orderByLambda); 83 } 84 85 return list.Skip((parameter.pageIndex - 1) * parameter.pageSize).Take(parameter.pageSize).Select(parameter.selectLambda).ToList(); 86 } 87 } 88 89 //取所需列 90 public class Person 91 { 92 public string Name { get; set; } 93 } 94 95 //封装方法参数 96 public class GetPageListParameter 97 { 98 public Expression > selectLambda { get; set; } 99 public Expression > whereLambda { get; set; }100 public Expression > orderByLambda { get; set; }101 public int pageSize { get; set; }102 public int pageIndex { get; set; }103 public bool isAsc { get; set; }104 }105 }