You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.2 KiB

2 years ago
  1. using OrmTest.Models;
  2. using SqlSugar;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. namespace OrmTest.Demo
  8. {
  9. public class SharedConnection : DemoBase
  10. {
  11. public static void Init()
  12. {
  13. StudentDal studentDal = new StudentDal();
  14. SchoolDal schoolDal = new SchoolDal();
  15. try
  16. {
  17. studentDal.BeginTran();
  18. Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());//0
  19. studentDal.AddStudent(new Student() { Name = "StudentTest" });
  20. schoolDal.AddSchool(new School() { Name = "SchoolTest" });//1
  21. Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());
  22. throw new Exception("error");
  23. }
  24. catch
  25. {
  26. studentDal.RollbackTran();
  27. Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());//0
  28. }
  29. }
  30. }
  31. public class StudentDal : BaseDao
  32. {
  33. public void AddStudent(Student sudent)
  34. {
  35. db.Insertable(sudent).ExecuteCommand();
  36. }
  37. }
  38. public class SchoolDal : BaseDao
  39. {
  40. public void AddSchool(School school)
  41. {
  42. db.Insertable(school).ExecuteCommand();
  43. }
  44. public int GetSchoolCount()
  45. {
  46. return db.Queryable<School>().Count();
  47. }
  48. }
  49. public class BaseDao
  50. {
  51. public SqlSugar.SqlSugarClient db { get { return GetInstance(); } }
  52. public void BeginTran()
  53. {
  54. db.Ado.BeginTran();
  55. }
  56. public void CommitTran()
  57. {
  58. db.Ado.CommitTran();
  59. }
  60. public void RollbackTran()
  61. {
  62. db.Ado.RollbackTran();
  63. }
  64. public SqlSugarClient GetInstance()
  65. {
  66. SqlSugarClient db = new SqlSugarClient(
  67. new ConnectionConfig()
  68. {
  69. ConnectionString = Config.ConnectionString,
  70. DbType = DbType.SqlServer,
  71. IsAutoCloseConnection = false,
  72. IsShardSameThread = true /*Shard Same Thread*/
  73. });
  74. return db;
  75. }
  76. }
  77. }