本篇介绍如何一次操作2个表,还是以 T_Student 和 T_Score 表为例。
场景一:如果客户端的页面是这样的,即提交的时候同时将学生信息和成绩信息提交过来,如下:
这时需要先写入学生表,然后再写入成绩表,新增操作的代码如下(使用事务):
public void OnPost() { //如果执行失败事务会自动回收,所以不需要显示执行 trans.Rollback(); using (IDbContextTransaction trans = _context.Database.BeginTransaction())//开启事务 { TStudent student = new TStudent { StuName = "雪宝", ClassCode = "4-1", ClassName = "四(1)班" }; _context.TStudents.Add(student);//新增学生 _context.SaveChanges(); //保存学生 TScore score = new TScore { ScoreId = 4,//为了演示,这里写死 StuId = student.StuId, //这里已经可以取到刚新增的学生编号 StuName = student.StuName, SubjectCode = "YUWEN", SubjectName = "语文", ExamScores = 86, ExamDate = DateTime.Now }; _context.TScores.Add(score);//新增成绩 _context.SaveChanges(); //保存成绩 trans.Commit(); //提交事务 } }
编译后执行,数据库值如下:
场景二:我们将场景一再演化一下,一次新增某个学生两科(语文、数学)成绩,画面如下:
提交的时候先保存学生表,然后将语文/数学成绩批量保存到成绩表,代码如下:
public void OnPost() { //如果执行失败事务会自动回收,所以不需要显示执行 trans.Rollback(); using (IDbContextTransaction trans = _context.Database.BeginTransaction())//开启事务 { TStudent student = new TStudent { StuName = "王子嘉", ClassCode = "4-1", ClassName = "四(1)班" }; _context.TStudents.Add(student); _context.SaveChanges(); //保存 TScore ywScore = new TScore { ScoreId = 5, StuId = student.StuId, StuName = student.StuName, SubjectCode = "YUWEN", SubjectName = "语文", ExamScores = 89, ExamDate = DateTime.Now }; TScore sxScore = new TScore { ScoreId = 6, StuId = student.StuId, StuName = student.StuName, SubjectCode = "SHUXUE", SubjectName = "数学", ExamScores = 97, ExamDate = DateTime.Now }; List<TScore> scoreList = new List<TScore>(); scoreList.Add(ywScore); scoreList.Add(sxScore); _context.TScores.AddRange(scoreList);//使用 AddRange() 批量新增,传入实体 List. _context.SaveChanges(); //保存 trans.Commit(); //提交事务 } }
编译后执行,结果如下: