DbDataReaderMapper.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System.Collections.Concurrent;
  2. using System.ComponentModel.DataAnnotations.Schema;
  3. using System.Data;
  4. using System.Data.Common;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Runtime.CompilerServices;
  8. using EasyDevCore.Common;
  9. using Microsoft.EntityFrameworkCore.Storage;
  10. namespace EasyDevCore.Database
  11. {
  12. /// <summary>
  13. /// Mapper <see cref="DbDataReader" /> to model of type />
  14. /// </summary>
  15. /// <typeparam name="T">Model type</typeparam>
  16. public class DbDataReaderMapper<T> where T : class, new()
  17. {
  18. private struct Prop
  19. {
  20. public int ColumnOrdinal;
  21. public string ColumnName;
  22. public Action<object, object> Setter { get; set; }
  23. }
  24. /// <summary>
  25. /// Contains different columns set information mapped to type <typeparamref name="T"/>.
  26. /// </summary>
  27. private static readonly ConcurrentDictionary<ulong, Prop[]> PropertiesCache = new ConcurrentDictionary<ulong, Prop[]>();
  28. private readonly DbDataReader _reader;
  29. private readonly Prop[] _properties;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="DbDataReaderMapper{T}"/> class.
  32. /// </summary>
  33. /// <param name="reader">The reader.</param>
  34. public DbDataReaderMapper(RelationalDataReader reader) : this(reader.DbDataReader)
  35. {
  36. }
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="DbDataReaderMapper{T}" /> class.
  39. /// </summary>
  40. /// <param name="reader">The reader.</param>
  41. public DbDataReaderMapper(DbDataReader reader)
  42. {
  43. _reader = reader;
  44. _properties = MapColumnsToProperties();
  45. }
  46. /// <summary>
  47. /// Gets the rows.
  48. /// </summary>
  49. /// <returns></returns>
  50. public IEnumerable<T> GetRows()
  51. {
  52. while (_reader.Read())
  53. {
  54. yield return MapNextRow();
  55. }
  56. }
  57. /// <summary>
  58. /// Gets the rows asynchronous.
  59. /// </summary>
  60. /// <param name="cancellationToken">The cancellation token.</param>
  61. /// <returns></returns>
  62. public async IAsyncEnumerable<T> GetRowsAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
  63. {
  64. while (await _reader.ReadAsync(cancellationToken).ConfigureAwait(false))
  65. {
  66. yield return await MapNextRowAsync().ConfigureAwait(false);
  67. }
  68. }
  69. /// <summary>
  70. /// Map <see cref="DbDataReader"/> to a T and apply an action on it for each row
  71. /// </summary>
  72. /// <param name="action">Action to apply to each row</param>
  73. public void Map(Action<T> action)
  74. {
  75. while (_reader.Read())
  76. {
  77. T row = MapNextRow();
  78. action(row);
  79. }
  80. }
  81. /// <summary>
  82. /// Map <see cref="DbDataReader"/> to a T and apply an action on it for each row
  83. /// </summary>
  84. /// <param name="action">Action to apply to each row</param>
  85. public Task MapAsync(Action<T> action)
  86. {
  87. return MapAsync(action, CancellationToken.None);
  88. }
  89. /// <summary>
  90. /// Map <see cref="DbDataReader"/> to a T and apply an action on it for each row
  91. /// </summary>
  92. /// <param name="action">Action to apply to each row</param>
  93. /// <param name="cancellationToken">The cancellation instruction, which propagates a notification that operations should be canceled</param>
  94. public async Task MapAsync(Action<T> action, CancellationToken cancellationToken)
  95. {
  96. while (await _reader.ReadAsync(cancellationToken).ConfigureAwait(false))
  97. {
  98. T row = await MapNextRowAsync(cancellationToken).ConfigureAwait(false);
  99. action(row);
  100. }
  101. }
  102. /// <summary>
  103. /// Maps the next row.
  104. /// </summary>
  105. /// <returns></returns>
  106. public T MapNextRow()
  107. {
  108. T row = new T();
  109. for (int i = 0; i < _properties.Length; ++i)
  110. {
  111. object value = _reader.IsDBNull(_properties[i].ColumnOrdinal) ? null : _reader.GetValue(_properties[i].ColumnOrdinal);
  112. try
  113. {
  114. _properties[i].Setter(row, value);
  115. }
  116. catch (Exception ex)
  117. {
  118. ex.Data["Mapping"] = $"Model[{_properties[i].ColumnName}] = Column[{_reader.GetName(_properties[i].ColumnOrdinal)}]";
  119. throw;
  120. }
  121. }
  122. return row;
  123. }
  124. /// <summary>
  125. /// Maps the next row asynchronous.
  126. /// </summary>
  127. /// <returns></returns>
  128. public Task<T> MapNextRowAsync()
  129. {
  130. return MapNextRowAsync(CancellationToken.None);
  131. }
  132. /// <summary>
  133. /// Maps the next row asynchronous.
  134. /// </summary>
  135. /// <param name="cancellationToken">The cancellation token.</param>
  136. /// <returns></returns>
  137. public async Task<T> MapNextRowAsync(CancellationToken cancellationToken)
  138. {
  139. T row = new T();
  140. for (int i = 0; i < _properties.Length; ++i)
  141. {
  142. object value = await _reader.IsDBNullAsync(_properties[i].ColumnOrdinal, cancellationToken).ConfigureAwait(false)
  143. ? null
  144. : _reader.GetValue(_properties[i].ColumnOrdinal);
  145. try
  146. {
  147. _properties[i].Setter(row, value);
  148. }
  149. catch (Exception ex)
  150. {
  151. ex.Data["Mapping"] = $"Column[{_reader.GetName(_properties[i].ColumnOrdinal)}] = Model[{_properties[i].ColumnName}]";
  152. throw;
  153. }
  154. }
  155. return row;
  156. }
  157. private Prop[] MapColumnsToProperties()
  158. {
  159. Type modelType = typeof(T);
  160. string[] columns = new string[_reader.FieldCount];
  161. Type[] colTypes = new Type[_reader.FieldCount];
  162. for (int i = 0; i < _reader.FieldCount; ++i)
  163. {
  164. columns[i] = _reader.GetName(i);
  165. colTypes[i] = _reader.GetFieldType(i);
  166. }
  167. ulong propKey = CheckSumHelper.CRC64(modelType.FullName + "|" + string.Join("|", columns) + "|" + string.Join("|", colTypes.Select(c => c.FullName)));
  168. if (PropertiesCache.TryGetValue(propKey, out var s))
  169. {
  170. return s;
  171. }
  172. var propertyInfos = modelType.GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite && !p.GetCustomAttributes<NotMappedAttribute>().Any())
  173. .Select(p => new { Property = p, Mapping = p.GetCustomAttribute<ColumnAttribute>() });
  174. var mappingFields = (from c in columns.Select((v, i) => new { Index = i, Name = v, ColType = colTypes[i] })
  175. from p in propertyInfos
  176. where c.Name.Equals(p.Mapping != null ? p.Mapping.Name : p.Property.Name, StringComparison.InvariantCultureIgnoreCase)
  177. select new { c.Index, p.Property, p.Mapping, c.ColType });
  178. var properties = new List<Prop>();
  179. ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
  180. ParameterExpression value = Expression.Parameter(typeof(object), "value");
  181. //MethodInfo changeTypeMethod = typeof(Convert).GetMethod("ChangeType", new[] { typeof(object), typeof(Type) });
  182. foreach (var fi in mappingFields)
  183. {
  184. PropertyInfo prop = fi.Property;
  185. // "x as T" is faster than "(T) x" if x is a reference type
  186. UnaryExpression instanceCast = prop.DeclaringType.IsValueType ? Expression.Convert(instance, prop.DeclaringType) : Expression.TypeAs(instance, prop.DeclaringType);
  187. UnaryExpression valueCast = prop.PropertyType.IsValueType ? Expression.Convert(value, prop.PropertyType) : Expression.TypeAs(value, prop.PropertyType); MethodCallExpression setterCall = Expression.Call(instanceCast, prop.GetSetMethod(), valueCast);
  188. var setter = (Action<object, object>)Expression.Lambda(setterCall, instance, value).Compile();
  189. Action<object, object> setterConvert = null;
  190. if (prop.PropertyType != fi.ColType)
  191. {
  192. setterConvert = ((Expression<Action<object, object>>)((o, v) => setter(o, v == null ? null : Convert.ChangeType(v, fi.Property.PropertyType)))).Compile();
  193. }
  194. properties.Add(new Prop
  195. {
  196. ColumnOrdinal = fi.Index,
  197. ColumnName = prop.Name,
  198. Setter = setterConvert == null ? setter : setterConvert
  199. });
  200. }
  201. Prop[] propertiesArray = properties.ToArray();
  202. PropertiesCache[propKey] = propertiesArray;
  203. return propertiesArray;
  204. }
  205. }
  206. }