Entity Framework常用方法及案例
⒈Skip(int count)
说明:跳过集合的前n个元素;延迟。即我们跳过给定的数目返回后面的结果集。
⒉Take(int count)
说明:获取集合的前n个元素;延迟。即只返回限定数量的结果集。
案例:分页查询
1 public IList<StudentScore> test1(int pageSize,int pageIndex) 2 { 3 //skip表示跳过多少条,Take表示取多少条 4 var list = _db.StudentScore.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); 5 return list; 6 }
⒊OrderBy
说明:按指定表达式对集合排序;延迟,默认是升序,加上descending表示降序,对应的扩展方法是 OrderBy和OrderByDescending
1 public IList<StudentScore> test2() 2 { 3 var list = _db.StudentScore.OrderBy(s => s.Id).ToList(); 4 var list2 = _db.StudentScore.OrderByDescending(s => s.Id).ToList(); 5 return list; 6 }
⒋Add
说明:添加一个实体
1 public int test4() 2 { 3 var student = new Student {SName = "fanqi",SSex = 1,SBirthday = new DateTime(1994,6,24) }; 4 var add = _db.Student.Add(student); 5 _db.SaveChanges(); 6 return add.Entity.Id; 7 }
⒌Remove
说明:删除一个实体
1 public void test5() 2 { 3 _db.Remove(new Student { Id = 9 }); 4 _db.SaveChanges(); 5 6 //Student user = new Student(){ Id = 9}; 7 //将对象添加到EF管理容器 8 //_db.Student.Attach(user); 9 //将对象包装类的标识状态变更为删除状态 10 //_db.Student.Remove(user); 11 //通知上下文将实体的变化保存到数据库中 12 //_db.SaveChanges(); 13 }
⒍Update
说明:更新一个实体
1 public void test6() 2 { 3 Student student = _db.Student.FirstOrDefault(f => f.Id == 7); 4 student.SName = "fanqi"; 5 _db.Student.Update(student); 6 _db.SaveChanges(); 7 8 //声明一个实体对象并赋初始值 9 //Student student = new Student { Id = 8, SName = "fanqi" }; 10 //将实体对象加入到EF对象容器中,并获取伪包装类对象 11 //EntityEntry<Student> entry = _db.Entry<Student>(student); 12 //将包装类对象的状态设置为unchanged 13 //entry.State = EntityState.Unchanged; 14 //设置实体对象被改变的属性 15 //entry.Property(a => a.SName).IsModified = true; 16 //通知上下文将实体的变化保存到数据库中 17 //_db.SaveChanges(); 18 }
⒎Join
说明:内连接
1 public dynamic test7() 2 { 3 var studentList = _db.Student; 4 var scoreList = _db.StudentScore; 5 var newList = studentList.Join(scoreList, stu => stu.Id, sco => sco.SId, (stu, sco) => new 6 { 7 studentId = stu.Id, 8 studentName = stu.SName, 9 studentSex = stu.SSex == 1?"男":"女", 10 scoreId = sco.Id, 11 courseId = sco.CId, 12 courseScoreNum = sco.Score 13 }); 14 return newList; 15 }
⒏GroupJoin
说明:左连接
1 public dynamic test8() 2 { 3 var studentList = _db.Student; 4 var scoreList = _db.StudentScore; 5 6 var newList = studentList.GroupJoin(scoreList, stu => stu.Id, sco => sco.SId, (stu, sco) => new 7 { 8 studentId = stu.Id, 9 studentName = stu.SName, 10 studentSex = stu.SSex == 1 ? "男" : "女", 11 sco 12 }); 13 return newList; 14 }