IUnitOfWork.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using XYY.Common.Standard;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Diagnostics;
  8. namespace XYY.Core.Standard.Data.Infrastructure
  9. {
  10. public interface IUnitOfWork : IDisposable
  11. {
  12. string ConnectionAddress { get; set; }
  13. int? CurrentId { get; set; }
  14. string CurrentName { get; set; }
  15. int? CustomerId { get; set; }
  16. IDbConnection Connection { get; set; }
  17. IDbTransaction Transaction { get; set; }
  18. List<DataPermission> DataPermission { get; set; }
  19. void Commit();
  20. void Rollback();
  21. }
  22. public class UnitOfWork : IUnitOfWork
  23. {
  24. public string ConnectionAddress { get; set; }
  25. private enum TransType
  26. {
  27. 提交事务,
  28. 回滚事务
  29. }
  30. public int? CurrentId { get; set; }
  31. public int? CustomerId { get; set; }
  32. public string CurrentName { get; set; }
  33. public IDbConnection Connection { get; set; }
  34. public IDbTransaction Transaction { get; set; }
  35. public UnitOfWork(IDbConnection dbConnection, string ConnectionAddress)
  36. {
  37. IsCommit = false;
  38. this.Connection = dbConnection;
  39. this.ConnectionAddress = ConnectionAddress;
  40. }
  41. private void SaveChanges(TransType trans)
  42. {
  43. if (!IsCommit && Connection != null && Connection.State == ConnectionState.Open && Transaction != null)
  44. {
  45. switch (trans)
  46. {
  47. case TransType.提交事务: Transaction.Commit(); break;
  48. case TransType.回滚事务: Transaction.Rollback(); break;
  49. }
  50. IsCommit = true;
  51. }
  52. if (Connection != null && Connection.State == ConnectionState.Open)
  53. {
  54. Connection.Close();
  55. }
  56. }
  57. private bool IsCommit { get; set; }
  58. public void Commit()
  59. {
  60. SaveChanges(TransType.提交事务);
  61. }
  62. public void Rollback()
  63. {
  64. SaveChanges(TransType.回滚事务);
  65. }
  66. public void Dispose()
  67. {
  68. Trace.WriteLine("UnitOfWork Dispose");
  69. //try
  70. //{
  71. // Commit();
  72. //}
  73. //catch (Exception)
  74. //{
  75. // Rollback();
  76. //}
  77. //finally
  78. //{
  79. // if (Connection.State != ConnectionState.Closed)
  80. // {
  81. // Connection.Close();
  82. // }
  83. //}
  84. //Commit();
  85. }
  86. public List<DataPermission> DataPermission { get; set; }
  87. }
  88. }