- 1 Students stu = new Students();
- 2 stu.StudentNO = 1833200160;
- 3 stu.StudentName = "露丝";
- 4 stu.StudentAge = 0;
- 5 stu.StudentSex = "女";
- 6 stu.StudentProvince = "";
- 7 stu.StudentPhone = "";
- 8
- 9 //将当前实例附加到上下文来处理
- 10 dbContext.Students.Attach(stu);
- 11
- 12 //写法一:
- 13 //这里修改了名字和性别,因为其他的属性字段是不可空的所以为了通过验证必须
- 14 //赋值(赋上了任意的值,但是我们并没有保存这些更改)
- 15 //dbContext.Entry<Students>(stu).Property("StudentName").IsModified = true;
- 16 //dbContext.Entry<Students>(stu).Property("StudentSex").IsModified = true;
- 17
- 18 //写法二:Lambda表达式
- 19 dbContext.Entry<Students>(stu).Property<string>(s => s.StudentName).IsModified = true;
- 20 dbContext.Entry<Students>(stu).Property<string>(s => s.StudentSex).IsModified = true;
- 21
- 22 int i = dbContext.SaveChanges();
- 23 string str = i == 1 ? "修改成功" : "修改失败";
- 24 Console.WriteLine(str);