标签:des style blog io ar color os 使用 sp
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 }
标签:des style blog io ar color os 使用 sp
原文地址:http://www.cnblogs.com/sunniest/p/4123560.html