利用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_Test>(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<T_Test, int> parameter=new GetPageListParameter<T_Test,int>(); 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<T_Test, int>(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<dynamic> GetPageList<T, TKey>(GetPageListParameter<T, TKey> parameter, out int count) where T : class 71 { 72 testEntities context = new testEntities(); 73 //注意顺序 74 count = context.Set<T>().Where<T>(parameter.whereLambda).Count(); 75 var list = context.Set<T>().Where<T>(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<T, TKey> 97 { 98 public Expression<Func<T, dynamic>> selectLambda { get; set; } 99 public Expression<Func<T, bool>> whereLambda { get; set; } 100 public Expression<Func<T, TKey>> orderByLambda { get; set; } 101 public int pageSize { get; set; } 102 public int pageIndex { get; set; } 103 public bool isAsc { get; set; } 104 } 105 }
时间: 2024-11-10 02:18:03