.Net 常用ORM框架對比:EF Core、FreeSql、SqlSuger (下篇)
阿新 • • 發佈:2020-12-21
前言:
本篇文章接上篇繼續講解:https://www.cnblogs.com/xl-tf/p/14163360.html
接下來就是具體的業務邏輯實現了;
一:在Api中如何使用
1. 新增EfCoreController 空Api控制器,用於實現EF Core的程式碼,編寫如下程式碼
1 [Route("api/[controller]")] 2 [ApiController] 3 public class EfCoreController : ControllerBase 4 { 5 private readonly ILogger<EfCoreController> _logger;6 private readonly IDbContextFactory _efDbContext; 7 public EfCoreController(ILogger<EfCoreController> logger, IDbContextFactory efDbContext) 8 { 9 this._logger = logger; 10 this._efDbContext = efDbContext; 11 } 12 }
2.新增FreeSqlController 空Api控制器,用於實現FreeSql的程式碼,編寫如下程式碼(FreeSql支援兩種方式:IFreeSql,DbContext)
1 [Route("api/[controller]")] 2 [ApiController] 3 public class FreeSqlController : ControllerBase 4 { 5 private readonly IFreeSql _freeSql; 6 private readonly FreeSqlContext _freeSqlContext; 7 private readonly ILogger<FreeSqlController> _logger;8 public FreeSqlController(FreeSqlContext freeSqlContext, IFreeSql freeSql, ILogger<FreeSqlController> logger) 9 { 10 this._freeSql = freeSql; 11 this._freeSqlContext = freeSqlContext; 12 this._logger = logger; 13 } 14 }
3.新增SqlSugerController 空Api控制器,用於實現SqlSuger的程式碼,編寫如下程式碼
1 [Route("api/[controller]")] 2 [ApiController] 3 public class SqlSugerController : ControllerBase 4 { 5 private readonly StudentService _studentService; 6 private readonly ClassGradeService _classGradeService; 7 private readonly CourseService _courseService; 8 private readonly MiddleStudentCourseService _middleStudentCourse; 9 private readonly MiddleClassCourseCervice _middleClassCourse; 10 private readonly ILogger<SqlSugerController> _logger; 11 public SqlSugerController(ILogger<SqlSugerController> logger, 12 StudentService studentService, 13 CourseService courseService, 14 MiddleStudentCourseService middleStudentCourse, 15 MiddleClassCourseCervice middleClassCourse, 16 ClassGradeService classGradeService) 17 { 18 this._studentService = studentService; 19 this._courseService = courseService; 20 this._classGradeService = classGradeService; 21 this._middleStudentCourse = middleStudentCourse; 22 this._middleClassCourse = middleClassCourse; 23 this._logger = logger; 24 } 25 }
二 :新增
1.EfCoreController中新增Action
1 /// <summary> 2 /// 新增班級 3 /// </summary> 4 /// <param name="name"></param> 5 /// <returns></returns> 6 [HttpPost("AddClass/{name}")] 7 public IActionResult AddClass(string name) 8 { 9 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 10 ClassGrade classGrade = new ClassGrade { Name = name }; 11 db.Add(classGrade); 12 db.SaveChanges(); 13 return Ok(classGrade.Id); 14 } 15 /// <summary> 16 /// 新增課程和老師 17 /// </summary> 18 /// <param name="name"></param> 19 /// <returns></returns> 20 [HttpPost("AddCourse/{name}")] 21 public IActionResult AddCourse(string name) 22 { 23 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 24 Course classGrade = new Course { Name = name, Teacher = name + "老師" }; 25 db.Add(classGrade); 26 db.SaveChanges(); 27 return Ok(classGrade.Id); 28 } 29 /// <summary> 30 /// 給班級新增課程 31 /// </summary> 32 /// <param name="classAddCourse"></param> 33 /// <returns></returns> 34 [HttpPost("ClassAddCourse")] 35 public IActionResult ClassAddCourse([FromBody] ClassAddCourse classAddCourse) 36 { 37 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 38 var date = db.Classs.Include(t => t.Classs) 39 .Where(t => t.Id == classAddCourse.ClassId).First(); 40 foreach (var i in classAddCourse.CourseIds) 41 { 42 if (!date.Classs.Select(t => t.Id).Contains(i)) 43 { 44 date.Classs.Add(new MiddleClassCourse 45 { 46 ClassId = date.Id, 47 CourseId = i 48 }); 49 } 50 } 51 return Ok(db.SaveChanges()); 52 } 53 /// <summary> 54 /// 插入學生 55 /// </summary> 56 /// <param name="student"></param> 57 /// <returns></returns> 58 [HttpPost("AddStudent")] 59 public IActionResult AddStudent([FromBody] AddStudent student) 60 { 61 try 62 { 63 StringBuilder str = new StringBuilder(); 64 str.AppendLine("====AddStudent===="); 65 66 Stopwatch stopwatch2 = new Stopwatch(); 67 stopwatch2.Start(); 68 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 69 List<Student> Students11 = new List<Student>(); 70 for (int i = 0; i < student.Count; i++) 71 { 72 Students11.Add(new Student 73 { 74 ClassId = student.ClassId, 75 Name = student.Count.ToString(), 76 Age = 20, 77 Sex = 1, 78 }); 79 } 80 db.Students.AddRange(Students11); 81 db.SaveChanges(); 82 stopwatch2.Stop(); 83 str.AppendLine($"DbContext插入{student.Count}條資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 84 85 _logger.LogInformation(str.ToString()); 86 return Ok(str.ToString()); 87 } 88 catch (Exception ex) 89 { 90 return Ok(ex.Message); 91 } 92 } 93 /// <summary> 94 /// 插入學生-帶選修課程 95 /// </summary> 96 /// <param name="course"></param> 97 /// <returns></returns> 98 [HttpPost("AddStudentCourse")] 99 public IActionResult AddStudentCourse([FromBody] AddStudentCourse course) 100 { 101 try 102 { 103 StringBuilder str = new StringBuilder(); 104 str.AppendLine("====AddStudentCourse===="); 105 106 Stopwatch stopwatch1 = new Stopwatch(); 107 stopwatch1.Start(); 108 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 109 for (int i = 0; i < course.StudentCount; i++) 110 { 111 db.Students.Add(new Student 112 { 113 ClassId = course.ClassId, 114 Name = i.ToString(), 115 Age = 22, 116 Sex = 0, 117 Courses = new List<MiddleStudentCourse> { new MiddleStudentCourse { CourseId = course.CourseId } } 118 }); 119 } 120 db.SaveChanges(); 121 stopwatch1.Stop(); 122 str.AppendLine($"方法1插入{course.StudentCount * 2}條資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 123 124 _logger.LogInformation(str.ToString()); 125 return Ok(str.ToString()); 126 } 127 catch (Exception ex) 128 { 129 return Ok(ex.Message); 130 } 131 }View Code
2.FreeSqlController中新增Action
1 /// <summary> 2 /// 新增班級 3 /// </summary> 4 /// <param name="name"></param> 5 /// <returns></returns> 6 [HttpPost("AddClass/{name}")] 7 public IActionResult AddClass(string name) 8 { 9 ClassGrade classGrade = new ClassGrade { Name = name }; 10 var classid = _freeSql.Insert(classGrade).ExecuteIdentity(); 11 return Ok(classid); 12 } 13 /// <summary> 14 /// 新增課程和老師 15 /// </summary> 16 /// <param name="name"></param> 17 /// <returns></returns> 18 [HttpPost("AddCourse/{name}")] 19 public IActionResult AddCourse(string name) 20 { 21 Course classGrade = new Course { Name = name, Teacher = name + "老師" }; 22 var classid = _freeSql.Insert(classGrade).ExecuteIdentity(); 23 return Ok(classid); 24 } 25 /// <summary> 26 /// 給班級新增課程 27 /// </summary> 28 /// <param name="classAddCourse"></param> 29 /// <returns></returns> 30 [HttpPost("ClassAddCourse")] 31 public IActionResult ClassAddCourse([FromBody] ClassAddCourse classAddCourse) 32 { 33 var date = _freeSql.Select<ClassGrade>() 34 .IncludeMany(t => t.Classs) 35 .Where(t => t.Id == classAddCourse.ClassId).First(); 36 var Classs = new List<MiddleClassCourse>(); 37 foreach (var i in classAddCourse.CourseIds) 38 { 39 if (!date.Classs.Select(t => t.Id).Contains(i)) 40 { 41 Classs.Add(new MiddleClassCourse 42 { 43 ClassId = date.Id, 44 CourseId = i 45 }); 46 } 47 } 48 return Ok(_freeSql.Insert(Classs).ExecuteAffrows()); 49 } 50 /// <summary> 51 /// 插入學生 52 /// </summary> 53 /// <param name="student"></param> 54 /// <returns></returns> 55 [HttpPost("AddStudent")] 56 public IActionResult AddStudent([FromBody] AddStudent student) 57 { 58 try 59 { 60 StringBuilder str = new StringBuilder(); 61 str.AppendLine("====AddStudent===="); 62 63 Stopwatch stopwatch2 = new Stopwatch(); 64 stopwatch2.Start(); 65 List<Student> Students11 = new List<Student>(); 66 for (int i = 0; i < student.Count; i++) 67 { 68 Students11.Add(new Student 69 { 70 ClassId = student.ClassId, 71 Name = student.Count.ToString(), 72 Age = 20, 73 Sex = 1, 74 }); 75 } 76 _freeSqlContext.Students.AddRange(Students11); 77 _freeSqlContext.SaveChanges(); 78 stopwatch2.Stop(); 79 str.AppendLine($"DbContext插入{student.Count}條資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 80 81 //Stopwatch stopwatch3 = new Stopwatch(); 82 //stopwatch3.Start(); 83 //List<Student> Students = new List<Student>(); 84 //for (int i = 0; i < student.count; i++) 85 //{ 86 // Students.Add( 87 // new Student 88 // { 89 // ClassId = student.classId, 90 // Name = student.count.ToString(), 91 // Age = 20, 92 // Sex = 1, 93 // }); 94 //} 95 //_freeSql.Insert<Student>(Students).ExecuteAffrows(); 96 //stopwatch3.Stop(); 97 //str.AppendLine($"批量插入{student.count}條資料耗時:" + stopwatch3.ElapsedMilliseconds.ToString()); 98 99 _logger.LogInformation(str.ToString()); 100 return Ok(str.ToString()); 101 } 102 catch (Exception ex) 103 { 104 return Ok(ex.Message); 105 } 106 } 107 /// <summary> 108 /// 插入學生-帶選修課程 109 /// </summary> 110 /// <param name="course"></param> 111 /// <returns></returns> 112 [HttpPost("AddStudentCourse")] 113 public IActionResult AddStudentCourse([FromBody] AddStudentCourse course) 114 { 115 try 116 { 117 StringBuilder str = new StringBuilder(); 118 str.AppendLine("====AddStudentCourse===="); 119 120 #region 自增主鍵限制,不能使用 121 //Stopwatch stopwatch1 = new Stopwatch(); 122 //stopwatch1.Start(); 123 //for (int i = 0; i < course.StudentCount; i++) 124 //{ 125 // _freeSqlContext.Students.Add(new Student 126 // { 127 // ClassId = course.ClassId, 128 // Name = i.ToString(), 129 // Age = 22, 130 // Sex = 0, 131 // Courses =new List<MiddleStudentCourse> { new MiddleStudentCourse { CourseId = course.CourseId } } 132 // }); 133 //} 134 //_freeSqlContext.SaveChanges(); 135 //stopwatch1.Stop(); 136 //str.AppendLine($"方法1插入{course.StudentCount * 2}條資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 137 #endregion 138 139 Stopwatch stopwatch2 = new Stopwatch(); 140 stopwatch2.Start(); 141 for (int i = 0; i < course.StudentCount; i++) 142 { 143 var id = _freeSql.Insert<Student>(new Student 144 { 145 ClassId = course.ClassId, 146 Name = i.ToString(), 147 Age = 22, 148 Sex = 0, 149 }).ExecuteIdentity(); 150 151 MiddleStudentCourse msc = new MiddleStudentCourse { StudentId = (int)id, CourseId = course.CourseId }; 152 _freeSql.Insert<MiddleStudentCourse>(msc).ExecuteAffrows(); 153 } 154 stopwatch2.Stop(); 155 str.AppendLine($"方法2插入{course.StudentCount * 2}條資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 156 157 _logger.LogInformation(str.ToString()); 158 return Ok(str.ToString()); 159 } 160 catch (Exception ex) 161 { 162 return Ok(ex.Message); 163 } 164 }View Code
3.SqlSugerController中新增Action
1 /// <summary> 2 /// 新增班級 3 /// </summary> 4 /// <param name="name"></param> 5 /// <returns></returns> 6 [HttpPost("AddClass/{name}")] 7 public IActionResult AddClass(string name) 8 { 9 ClassGrade classGrade = new ClassGrade { Name = name }; 10 var classid = _classGradeService.Insert(classGrade); 11 return Ok(classid); 12 } 13 /// <summary> 14 /// 新增課程和老師 15 /// </summary> 16 /// <param name="name"></param> 17 /// <returns></returns> 18 [HttpPost("AddCourse/{name}")] 19 public IActionResult AddCourse(string name) 20 { 21 Course classGrade = new Course { Name = name, Teacher = name + "老師" }; 22 return Ok(_courseService.Insert(classGrade)); 23 } 24 /// <summary> 25 /// 給班級新增課程 26 /// </summary> 27 /// <param name="classAddCourse"></param> 28 /// <returns></returns> 29 [HttpPost("ClassAddCourse")] 30 public IActionResult ClassAddCourse([FromBody] ClassAddCourse classAddCourse) 31 { 32 33 var eds = _middleClassCourse.AsQueryable().Where(t => t.ClassId == classAddCourse.ClassId).ToList(); 34 var Classs = new List<MiddleClassCourse>(); 35 foreach (var i in classAddCourse.CourseIds) 36 { 37 if (!eds.Select(t => t.CourseId).Contains(i)) 38 { 39 Classs.Add(new MiddleClassCourse 40 { 41 ClassId = classAddCourse.ClassId, 42 CourseId = i 43 }); 44 } 45 } 46 return Ok(_middleClassCourse.InsertRange(Classs)); 47 } 48 /// <summary> 49 /// 插入學生 50 /// </summary> 51 /// <param name="student"></param> 52 /// <returns></returns> 53 [HttpPost("AddStudent")] 54 public IActionResult AddStudent([FromBody] AddStudent student) 55 { 56 try 57 { 58 StringBuilder str = new StringBuilder(); 59 str.AppendLine("====AddStudent===="); 60 61 Stopwatch stopwatch3 = new Stopwatch(); 62 stopwatch3.Start(); 63 List<Student> Students = new List<Student>(); 64 for (int i = 0; i < student.Count; i++) 65 { 66 Students.Add( 67 new Student 68 { 69 ClassId = student.ClassId, 70 Name = student.Count.ToString(), 71 Age = 20, 72 Sex = 1, 73 }); 74 } 75 _studentService.InsertRange(Students); 76 stopwatch3.Stop(); 77 str.AppendLine($"批量插入{student.Count}條資料耗時:" + stopwatch3.ElapsedMilliseconds.ToString()); 78 79 _logger.LogInformation(str.ToString()); 80 return Ok(str.ToString()); 81 } 82 catch (Exception ex) 83 { 84 return Ok(ex.Message); 85 } 86 } 87 /// <summary> 88 /// 插入學生-帶選修課程 89 /// </summary> 90 /// <param name="course"></param> 91 /// <returns></returns> 92 [HttpPost("AddStudentCourse")] 93 public IActionResult AddStudentCourse([FromBody] AddStudentCourse course) 94 { 95 try 96 { 97 StringBuilder str = new StringBuilder(); 98 str.AppendLine("====AddStudentCourse===="); 99 100 Stopwatch stopwatch2 = new Stopwatch(); 101 stopwatch2.Start(); 102 var service2 = _studentService.AsSugarClient(); 103 var service3 = _middleStudentCourse.AsSugarClient(); 104 for (int i = 0; i < course.StudentCount; i++) 105 { 106 var id = service2.Insertable(new Student() 107 { 108 Age = 18, 109 ClassId = course.ClassId, 110 Name = i.ToString(), 111 Sex = 1, 112 Id = 0,//自增列 113 114 }).ExecuteReturnIdentity(); 115 var Courses = new List<MiddleStudentCourse>() { new MiddleStudentCourse 116 { 117 CourseId = course.CourseId, 118 StudentId =id 119 } 120 }; 121 service3.Insertable(Courses).ExecuteCommand(); 122 } 123 stopwatch2.Stop(); 124 str.AppendLine($"方法1 單條插入{course.StudentCount * 2}條資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 125 126 //Stopwatch stopwatch1 = new Stopwatch(); 127 //stopwatch1.Start(); 128 //var service = _studentService.AsSugarClient(); 129 //for (int i = 0; i < course.StudentCount; i++) 130 //{ 131 // service.Insertable(new Student() 132 // { 133 // Age = 18, 134 // ClassId = course.ClassId, 135 // Name = i.ToString(), 136 // Sex = 1, 137 // Id = 0,//自增列 138 // Courses = new List<MiddleStudentCourse>() { new MiddleStudentCourse 139 // { 140 // CourseId = course.CourseId, 141 // StudentId =0//需要自動獲取訂單的自增列 142 // } 143 // } 144 // }) 145 // .AddSubList(it => it.Courses.First().StudentId)//設定item表的OrderId等於訂單自增列 146 // .ExecuteReturnPrimaryKey(); 147 //} 148 //stopwatch1.Stop(); 149 //str.AppendLine($"方法2 單條插入{course.StudentCount * 2}條資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 150 151 _logger.LogInformation(str.ToString()); 152 return Ok(str.ToString()); 153 } 154 catch (Exception ex) 155 { 156 return Ok(ex.Message); 157 } 158 }View Code 4.執行結果對比: 三:查詢
1.EfCoreController中新增Action
1 /// <summary> 2 /// 查詢學生 3 /// </summary> 4 /// <param name="id"></param> 5 /// <returns></returns> 6 [HttpGet("GetStudent/{id}")] 7 public IActionResult GetStudent(int id) 8 { 9 try 10 { 11 StringBuilder str = new StringBuilder(); 12 str.AppendLine("====GetStudent===="); 13 14 Stopwatch stopwatch1 = new Stopwatch(); 15 stopwatch1.Start(); 16 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Read); 17 var student1 = db.Students 18 .Include(a => a.Class) 19 .Include(a => a.Courses).ThenInclude(t => t.Course) 20 .Where(a => a.Id == id) 21 .Select(a => new StudentDto 22 { 23 ClassName = a.Class.Name, 24 //CourseIds = a.Courses.Select(t => t.CourseId).ToList(), 25 //Courses = a.Courses.Select(t => t.Course).ToList() 26 }).AsNoTracking() 27 .First(); 28 29 stopwatch1.Stop(); 30 str.AppendLine($"查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 31 32 _logger.LogInformation(str.ToString()); 33 return Ok(student1); 34 } 35 catch (Exception ex) 36 { 37 return Ok(ex.Message); 38 } 39 } 40 /// <summary> 41 /// 查詢班級中的所有學生 42 /// </summary> 43 /// <param name="id"></param> 44 /// <returns></returns> 45 [HttpGet("GetClassStudent/{id}")] 46 public IActionResult GetClassStudent(int id) 47 { 48 try 49 { 50 StringBuilder str = new StringBuilder(); 51 str.AppendLine("====GetClassStudent===="); 52 53 Stopwatch stopwatch2 = new Stopwatch(); 54 stopwatch2.Start(); 55 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Read); 56 var students = db.Classs 57 .Include(a => a.Students) 58 .Where(a => a.Id == id) 59 .AsNoTracking() 60 .First(); 61 stopwatch2.Stop(); 62 str.AppendLine($"查詢資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 63 64 _logger.LogInformation(str.ToString()); 65 return Ok(str.ToString()); 66 } 67 catch (Exception ex) 68 { 69 return Ok(ex.Message); 70 } 71 } 72 /// <summary> 73 /// 查詢學生的所有課程 74 /// </summary> 75 /// <param name="id"></param> 76 /// <returns></returns> 77 [HttpGet("GetStudentCourse/{id}")] 78 public IActionResult GetStudentCourse(int id) 79 { 80 try 81 { 82 StringBuilder str = new StringBuilder(); 83 str.AppendLine("====GetStudentCourse===="); 84 85 Stopwatch stopwatch1 = new Stopwatch(); 86 stopwatch1.Start(); 87 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Read); 88 var student = db.Students 89 .Where(t => t.Id == id).First(); 90 91 var item1 = (from a in db.Set<MiddleClassCourse>() 92 join b in db.Set<Course>() on a.CourseId equals b.Id 93 select new {a.ClassId, b.Id,b.Name}) 94 .Where(t => t.ClassId == student.ClassId) 95 .Select(a => new { a.Id,a.Name}) 96 .ToList(); 97 98 var item2 = (from a in db.Set<MiddleStudentCourse>() 99 join b in db.Set<Course>() on a.CourseId equals b.Id 100 select new {a.StudentId, b.Id, b.Name }) 101 .Where(t => t.StudentId == id) 102 .Select(a => new { a.Id, a.Name }) 103 .ToList(); 104 105 item1.AddRange(item2); 106 stopwatch1.Stop(); 107 str.AppendLine($"查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 108 109 _logger.LogInformation(str.ToString()); 110 return Ok(item1); 111 } 112 catch (Exception ex) 113 { 114 return Ok(ex.Message); 115 } 116 }
2.FreeSqlController中新增Action
1 /// <summary> 2 /// 查詢學生 3 /// </summary> 4 /// <param name="id"></param> 5 /// <returns></returns> 6 [HttpGet("GetStudent/{id}")] 7 public IActionResult GetStudent(int id) 8 { 9 try 10 { 11 StringBuilder str = new StringBuilder(); 12 str.AppendLine("====GetStudent===="); 13 14 15 Stopwatch stopwatch1 = new Stopwatch(); 16 stopwatch1.Start(); 17 var student1 = _freeSql.Select<Student>() 18 .Include(a => a.Class) 19 .IncludeMany(a => a.Courses, then => then.Include(t => t.Course)) 20 .Where(a => a.Id == id) 21 .First(a => new StudentDto 22 { 23 ClassName = a.Class.Name, 24 //CourseIds = a.Courses.AsSelect().ToList(a => a.CourseId)//一對多失敗 25 //Courses = a.Courses.AsSelect().ToList(a => a.Course),//一對多失敗 26 //Courses = a.Courses.AsSelect().ToList(t => new Course { Id = t.Course.Id, Name = t.Course.Name })//一對多失敗 27 }); 28 29 stopwatch1.Stop(); 30 str.AppendLine($"IFreeSql查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 31 32 { 33 //Stopwatch stopwatch2 = new Stopwatch(); 34 //stopwatch2.Start(); 35 //var student = _freeSqlContext.Students.Select 36 // .Include(a => a.Class) 37 // .IncludeMany(a => a.Courses, then => then.Include(t => t.Course)) 38 // .Where(a => a.Id == id + 1) 39 // .First(a => new StudentDto 40 // { 41 // ClassName = a.Class.Name, 42 // }); 43 //stopwatch2.Stop(); 44 //str.AppendLine($"DbContext查詢資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 45 } 46 47 _logger.LogInformation(str.ToString()); 48 return Ok(student1); 49 } 50 catch (Exception ex) 51 { 52 return Ok(ex.Message); 53 } 54 } 55 /// <summary> 56 /// 查詢班級中的所有學生 57 /// </summary> 58 /// <param name="id"></param> 59 /// <returns></returns> 60 [HttpGet("GetClassStudent/{id}")] 61 public IActionResult GetClassStudent(int id) 62 { 63 try 64 { 65 StringBuilder str = new StringBuilder(); 66 str.AppendLine("====GetClassStudent===="); 67 68 Stopwatch stopwatch2 = new Stopwatch(); 69 stopwatch2.Start(); 70 var students = _freeSqlContext.ClassGrades.Select 71 .IncludeMany(a => a.Students) 72 .Where(a => a.Id == id) 73 .First(); 74 stopwatch2.Stop(); 75 str.AppendLine($"DbContext查詢資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 76 77 { 78 //Stopwatch stopwatch1 = new Stopwatch(); 79 //stopwatch1.Start(); 80 //var students1 = _freeSql.Select<ClassGrade>() 81 // .IncludeMany(a => a.Students) 82 // .Where(a => a.Id == id) 83 // .ToSql(); 84 //stopwatch1.Stop(); 85 //str.AppendLine($"IFreeSql查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 86 } 87 88 _logger.LogInformation(str.ToString()); 89 return Ok(str.ToString()); 90 } 91 catch (Exception ex) 92 { 93 return Ok(ex.Message); 94 } 95 } 96 /// <summary> 97 /// 查詢學生的所有課程 98 /// </summary> 99 /// <param name="id"></param> 100 /// <returns></returns> 101 [HttpGet("GetStudentCourse/{id}")] 102 public IActionResult GetStudentCourse(int id) 103 { 104 try 105 { 106 StringBuilder str = new StringBuilder(); 107 str.AppendLine("====GetStudentCourse===="); 108 109 Stopwatch stopwatch1 = new Stopwatch(); 110 stopwatch1.Start(); 111 var student = _freeSql.Select<Student>().Where(t => t.Id == id).First(); 112 var item1 = _freeSql.Select<MiddleClassCourse>().From<Course>((a, b) => a 113 .LeftJoin(a => a.CourseId == b.Id) 114 .Where(a => a.ClassId == student.ClassId)) 115 .ToList((a, b) => new { b.Id, b.Name }); 116 117 var item2 = _freeSql.Select<MiddleStudentCourse>().From<Course>((a, b) => a 118 .LeftJoin(a => a.CourseId == b.Id) 119 .Where(a => a.StudentId == id)) 120 .ToList((a, b) => new { b.Id, b.Name }); 121 122 item1.AddRange(item2); 123 124 stopwatch1.Stop(); 125 str.AppendLine($"查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 126 127 _logger.LogInformation(str.ToString()); 128 return Ok(item1); 129 } 130 catch (Exception ex) 131 { 132 return Ok(ex.Message); 133 } 134 }
3.SqlSugerController中新增Action
1 /// <summary> 2 /// 查詢學生 3 /// </summary> 4 /// <param name="id"></param> 5 /// <returns></returns> 6 [HttpGet("GetStudent/{id}")] 7 public IActionResult GetStudent(int id) 8 { 9 try 10 { 11 StringBuilder str = new StringBuilder(); 12 str.AppendLine("====GetStudent===="); 13 14 Stopwatch stopwatch2 = new Stopwatch(); 15 stopwatch2.Start(); 16 var student1 = _studentService.AsQueryable() 17 .Mapper((it, cache) => 18 { 19 var allCourses = cache.Get(ol => 20 { 21 var olIds = ol.Select(t => t.Id).ToList(); 22 return _middleStudentCourse.AsQueryable() 23 .In(a => a.StudentId, olIds) 24 .Mapper(b => b.Course, b => b.CourseId).ToList(); 25 }); 26 it.Courses = allCourses.Where(i => i.StudentId == it.Id).ToList(); 27 }) 28 .Mapper(a => a.Class, a => a.ClassId) 29 .Where(a => a.Id == id) 30 .Select(t => new StudentDto()) 31 .First(); 32 stopwatch2.Stop(); 33 str.AppendLine($"方法2查詢資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 34 35 { 36 //Stopwatch stopwatch1 = new Stopwatch(); 37 //stopwatch1.Start(); 38 //var student = _studentService.AsQueryable() 39 // //.Mapper((it, cache) => 40 // //{ 41 // // var allCourses = cache.GetListByPrimaryKeys<MiddleStudentCourse>(vmodel => vmodel.Id); 42 // // it.Courses = allCourses.Where(i => i.StudentId == it.Id).ToList();//一對多載入失敗 43 // //}) 44 // .Mapper(a => a.Class, a => a.ClassId) 45 // .Where(a => a.Id == id) 46 // //.Select(t => new StudentDto()) 47 // //.Select(t => new StudentDto 48 // //{ 49 // // Age = t.Age, 50 // // //ClassName = t.Class.Name//無法實現 51 // //}) 52 // .First(); 53 //stopwatch1.Stop(); 54 //str.AppendLine($"方法1查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 55 } 56 57 _logger.LogInformation(str.ToString()); 58 return Ok(str.ToString()); 59 } 60 catch (Exception ex) 61 { 62 return Ok(ex.Message); 63 } 64 } 65 66 /// <summary> 67 /// 查詢班級中的所有學生 68 /// </summary> 69 /// <param name="id"></param> 70 /// <returns></returns> 71 [HttpGet("GetClassStudent/{id}")] 72 public IActionResult GetClassStudent(int id) 73 { 74 try 75 { 76 StringBuilder str = new StringBuilder(); 77 str.AppendLine("====GetClassStudent===="); 78 79 Stopwatch stopwatch1 = new Stopwatch(); 80 stopwatch1.Start(); 81 82 var students = _classGradeService.AsQueryable() 83 .Mapper((it, cache) => 84 { 85 List<Student> allStudents = cache.Get(ol => 86 { 87 var allStudentIds = ol.Select(x => x.Id).ToList(); 88 return _studentService.AsQueryable() 89 .In(a => a.ClassId, allStudentIds) 90 .ToList(); 91 }); 92 it.Students = allStudents.Where(a => a.ClassId == it.Id).ToList(); 93 }) 94 .Where(a => a.Id == id) 95 .First(); 96 stopwatch1.Stop(); 97 str.AppendLine($"查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 98 99 _logger.LogInformation(str.ToString()); 100 return Ok(students); 101 } 102 catch (Exception ex) 103 { 104 return Ok(ex.Message); 105 } 106 } 107 /// <summary> 108 /// 查詢學生的所有課程 109 /// </summary> 110 /// <param name="id"></param> 111 /// <returns></returns> 112 [HttpGet("GetStudentCourse/{id}")] 113 public IActionResult GetStudentCourse(int id) 114 { 115 try 116 { 117 StringBuilder str = new StringBuilder(); 118 str.AppendLine("====GetStudentCourse===="); 119 120 Stopwatch stopwatch1 = new Stopwatch(); 121 stopwatch1.Start(); 122 123 var student = _studentService.AsQueryable().Where(t => t.Id == id).First(); 124 var db = _studentService.AsSugarClient(); 125 var item1 = db.Queryable<MiddleClassCourse, Course>((a, b) => new JoinQueryInfos( 126 JoinType.Left, a.CourseId == b.Id 127 )) 128 .Where(a => a.ClassId == student.ClassId) 129 .Select((a, b) => new 130 { 131 b.Id, 132 b.Name 133 }).ToList(); 134 var item2 = db.Queryable<MiddleStudentCourse, Course>((a, b) => new JoinQueryInfos( 135 JoinType.Left, a.CourseId == b.Id 136 )) 137 .Where(a => a.StudentId == id) 138 .Select((a, b) => new 139 { 140 b.Id, 141 b.Name 142 }).ToList(); 143 item1.AddRange(item2); 144 145 stopwatch1.Stop(); 146 str.AppendLine($"查詢資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 147 148 _logger.LogInformation(str.ToString()); 149 return Ok(item1); 150 } 151 catch (Exception ex) 152 { 153 return Ok(ex.Message); 154 } 155 }4.執行結果對比: 四:修改
1.EfCoreController中新增Action
1 /// <summary> 2 /// 修改學生名 3 /// </summary> 4 /// <param name="student"></param> 5 /// <returns></returns> 6 [HttpPost("UpdateStudent")] 7 public IActionResult UpdateStudent([FromBody] UpdateStudent student) 8 { 9 try 10 { 11 StringBuilder str = new StringBuilder(); 12 str.AppendLine("====UpdateStudent===="); 13 14 Stopwatch stopwatch1 = new Stopwatch(); 15 stopwatch1.Start(); 16 var date = new Student { Id = student.Id, Age = student.Age, Sex = student.Sex, Name = student.Name }; 17 var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 18 db.Students.Attach(date); 19 db.Entry(date).Property(p => p.Name).IsModified = true; 20 db.Entry(date).Property(p => p.Sex).IsModified = true; 21 db.Entry(date).Property(p => p.Age).IsModified = true; 22 db.SaveChanges(); 23 stopwatch1.Stop(); 24 str.AppendLine($"指定列修改資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 25 26 //Stopwatch stopwatch3 = new Stopwatch(); 27 //stopwatch3.Start(); 28 //var db = _efDbContext.ConnWriteOrRead(WriteAndReadEnum.Write); 29 //var date = db.Students.Where(a => a.Id == student.Id).First(); 30 //date.Name = student.Name; 31 //date.Sex = student.Sex; 32 //date.Age = student.Age; 33 //db.SaveChanges(); 34 //stopwatch3.Stop(); 35 //str.AppendLine($"DbContext修改資料耗時:" + stopwatch3.ElapsedMilliseconds.ToString()); 36 37 38 //方法3:使用EntityFrameworkCore.Extensions 39 _logger.LogInformation(str.ToString()); 40 return Ok(str.ToString()); 41 } 42 catch (Exception ex) 43 { 44 return Ok(ex.Message); 45 } 46 }
2.FreeSqlController中新增Action
1 /// <summary> 2 /// 修改學生名 3 /// </summary> 4 /// <param name="student"></param> 5 /// <returns></returns> 6 [HttpPost("UpdateStudent")] 7 public IActionResult UpdateStudent([FromBody] UpdateStudent student) 8 { 9 try 10 { 11 StringBuilder str = new StringBuilder(); 12 str.AppendLine("====UpdateStudent===="); 13 14 Stopwatch stopwatch3 = new Stopwatch(); 15 stopwatch3.Start(); 16 _freeSqlContext.Students 17 .Where(a => a.Id == student.Id) 18 .ToUpdate() 19 .Set(a => a.Name, student.Name) 20 .Set(a => a.Age, student.Age) 21 .Set(a => a.Sex, student.Sex) 22 .ExecuteAffrows(); 23 _freeSqlContext.SaveChanges(); 24 stopwatch3.Stop(); 25 str.AppendLine($"DbContext修改資料耗時:" + stopwatch3.ElapsedMilliseconds.ToString()); 26 27 { 28 //Stopwatch stopwatch1 = new Stopwatch(); 29 //stopwatch1.Start(); 30 //_freeSql.Update<Student>() 31 // .Set(a => a.Name, student.Name) 32 // .Set(a => a.Sex, student.Sex) 33 // .Set(a => a.Age, student.Age) 34 // .Where(a => a.Id == student.Id) 35 // .ExecuteAffrows(); 36 //stopwatch1.Stop(); 37 //str.AppendLine($"IFreeSql 方法1 修改資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 38 39 //Stopwatch stopwatch4 = new Stopwatch(); 40 //stopwatch4.Start(); 41 //var repo = _freeSql.GetRepository<Student>(); 42 //var item = new Student { Id = student.Id }; 43 //repo.Attach(item); //此時快照 item 44 //item.Name = student.Name; 45 //item.Sex = student.Sex; 46 //item.Age = student.Age; 47 //repo.Update(item); //對比快照時的變化 48 //stopwatch4.Stop(); 49 //str.AppendLine($"Repository修改資料耗時:" + stopwatch4.ElapsedMilliseconds.ToString()); 50 } 51 52 _logger.LogInformation(str.ToString()); 53 return Ok(str.ToString()); 54 } 55 catch (Exception ex) 56 { 57 return Ok(ex.Message); 58 } 59 }
3.SqlSugerController中新增Action
1 /// <summary> 2 /// 修改學生名 3 /// </summary> 4 /// <param name="student"></param> 5 /// <returns></returns> 6 [HttpPost("UpdateStudent")] 7 public IActionResult UpdateStudent([FromBody] UpdateStudent student) 8 { 9 try 10 { 11 StringBuilder str = new StringBuilder(); 12 str.AppendLine("====UpdateStudent===="); 13 14 Stopwatch stopwatch1 = new Stopwatch(); 15 stopwatch1.Start(); 16 _studentService.Update(t => new Student 17 { 18 Name = student.Name, 19 Age = student.Age, 20 Sex = student.Sex 21 }, t => t.Id == student.Id); 22 stopwatch1.Stop(); 23 str.AppendLine($"方法1 修改資料耗時:" + stopwatch1.ElapsedMilliseconds.ToString()); 24 25 { 26 //Stopwatch stopwatch2 = new Stopwatch(); 27 //stopwatch2.Start(); 28 //_studentService.AsSugarClient().Updateable<Student>() 29 // .SetColumns(t => t.Name == student.Name) 30 // .SetColumns(t => t.Age == student.Age) 31 // .SetColumns(t => t.Sex == student.Sex) 32 // .Where(a => a.Id == student.Id) 33 // .ExecuteCommand(); 34 //stopwatch2.Stop(); 35 //str.AppendLine($"方法2 修改資料耗時:" + stopwatch2.ElapsedMilliseconds.ToString()); 36 } 37 38 _logger.LogInformation(str.ToString()); 39 return Ok(str.ToString()); 40 } 41 catch (Exception ex) 42 { 43 return Ok(ex.Message); 44 } 45 }4.執行結果對比:
五:總結
最後我決定選擇了使用FreeSql,算是折中方案吧。