QueryEnumerator.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using Ant.Core;
  2. using Ant.Data;
  3. using Ant.Mapper;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Linq;
  9. using System.Text;
  10. namespace Ant.Query.Internals
  11. {
  12. static class QueryEnumeratorCreator
  13. {
  14. public static IEnumerator<T> CreateEnumerator<T>(DataAccess dbSession, DbCommandFactor commandFactor)
  15. {
  16. return new QueryEnumerator<T>(dbSession, commandFactor);
  17. }
  18. internal struct QueryEnumerator<T> : IEnumerator<T>
  19. {
  20. DataAccess db;
  21. DbCommandFactor _commandFactor;
  22. IObjectActivator _objectActivator;
  23. IDataReader _reader;
  24. T _current;
  25. bool _hasFinished;
  26. bool _disposed;
  27. public QueryEnumerator(DataAccess dbSession, DbCommandFactor commandFactor)
  28. {
  29. this.db = dbSession;
  30. this._commandFactor = commandFactor;
  31. this._objectActivator = commandFactor.ObjectActivator;
  32. this._reader = null;
  33. this._current = default(T);
  34. this._hasFinished = false;
  35. this._disposed = false;
  36. }
  37. public T Current { get { return this._current; } }
  38. object IEnumerator.Current { get { return this._current; } }
  39. /// <summary>
  40. /// 指针获取数据
  41. /// </summary>
  42. /// <returns></returns>
  43. public bool MoveNext()
  44. {
  45. if (this._hasFinished || this._disposed)
  46. return false;
  47. if (this._reader == null)
  48. {
  49. //TODO 执行 sql 语句,获取 DataReader
  50. this._reader = this.db.ExecuteReader(this._commandFactor.CommandText, this._commandFactor.Parameters, CommandBehavior.Default, CommandType.Text);
  51. }
  52. if (this._reader.Read())
  53. {
  54. this._current = (T)this._objectActivator.CreateInstance(this._reader);
  55. return true;
  56. }
  57. else
  58. {
  59. this._reader.Close();
  60. this.db.Close();
  61. this._current = default(T);
  62. this._hasFinished = true;
  63. return false;
  64. }
  65. }
  66. /// <summary>
  67. /// 释放内存
  68. /// </summary>
  69. public void Dispose()
  70. {
  71. if (this._disposed)
  72. return;
  73. if (this._reader != null)
  74. {
  75. if (!this._reader.IsClosed)
  76. this._reader.Close();
  77. this._reader.Dispose();
  78. this._reader = null;
  79. }
  80. if (!this._hasFinished)
  81. {
  82. this.db.Close();
  83. this._hasFinished = true;
  84. }
  85. this._current = default(T);
  86. this._disposed = true;
  87. }
  88. public void Reset()
  89. {
  90. throw new NotSupportedException();
  91. }
  92. }
  93. }
  94. }