EF 增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using ( var dc = new SchoolContext()) { ////GRADE g = new GRADE() { GradeId=2 }; //var greadeinfo = dc.Grades.Find(2); //STUDENT stu = new STUDENT() { STUDENTID = 3, STUDENTNAME = "李四", HEIGHT = 180.5F, WEIGHT = 140.5F, DATEOFBIRTH = DateTime.Now, PHOTO = "987654321", GRADE= greadeinfo }; ////dc.Grades.Add(g); //dc.Students.Add(stu); //dc.SaveChanges(); // 查询内容 //IQueryable<STUDENT> stu = dc.Students; //foreach (var item in stu) //{ // MessageBox.Show(item.STUDENTID+" "+item.STUDENTNAME); //} //如果查询内容为空 //var stu=dc.Students.Where(t => t.STUDENTID == 5).FirstOrDefault(); //if(stu!=null) //{ // MessageBox.Show(stu.STUDENTID + " " + stu.STUDENTNAME); //} //排序 //IQueryable<STUDENT> stu = dc.Students.OrderBy(t => t.STUDENTID).ThenBy(t => t.GRADE); //foreach (var item in stu) //{ // MessageBox.Show(item.STUDENTID + " " + item.STUDENTNAME); //} //修改方法1 //var stu = dc.Students.Find(1); //if(stu!=null) //{ // stu.STUDENTNAME = "小张"; //} //dc.SaveChanges(); //修改方法2 通过自己创建的对象 //STUDENT stu = new STUDENT() { STUDENTID=3, STUDENTNAME="小三" };// 将对象加入EF容器,并获取当前实体对象的状态管理对象 //DbEntityEntry<STUDENT> s=dc.Entry<STUDENT>(stu); //s.State = System.Data.Entity.EntityState.Unchanged; //s.Property("STUDENTNAME").IsModified=true; //dc.SaveChanges(); //修改方法3 与 方法2 作用一样 STUDENT stu = new STUDENT() { STUDENTID = 2, STUDENTNAME = "小三1" }; var s = dc.Students.Attach(stu); s.STUDENTNAME = "小er" ; dc.SaveChanges(); //删除内容 //STUDENT stu = new STUDENT() { STUDENTID = 3, STUDENTNAME = "小三1" }; //dc.Students.Attach(stu); //dc.Students.Remove(stu); //dc.SaveChanges(); //MessageBox.Show("创建成功"); } |