DbContextExtensions.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using Microsoft.EntityFrameworkCore;
  2. using MySql.Data.MySqlClient;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Data;
  7. using System.Data.Common;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. namespace Dfs.WayneChina.SpsDbManager
  12. {
  13. public static class DbContextExtensions
  14. {
  15. public static MySqlCommand LoadStoredProc(this DbContext context, string storedProcName)
  16. {
  17. var cmd = context.Database.GetDbConnection().CreateCommand();
  18. cmd.CommandText = storedProcName;
  19. cmd.CommandType = CommandType.StoredProcedure;
  20. return (MySqlCommand)cmd;
  21. }
  22. public static MySqlCommand WithSqlParam(this MySqlCommand cmd, string paramName, object paramValue)
  23. {
  24. if (string.IsNullOrEmpty(cmd.CommandText))
  25. {
  26. throw new InvalidOperationException("Call LoadStoredProc before using this method");
  27. }
  28. var param = cmd.CreateParameter();
  29. param.ParameterName = paramName;
  30. param.Value = paramValue;
  31. cmd.Parameters.Add(param);
  32. return cmd;
  33. }
  34. public static MySqlCommand WithSqlParam(this MySqlCommand cmd, MySqlDbType dbType, string paramName, object paramValue)
  35. {
  36. if (string.IsNullOrEmpty(cmd.CommandText))
  37. {
  38. throw new InvalidOperationException("Call LoadStoredProc before using this method");
  39. }
  40. var param = cmd.CreateParameter();
  41. param.ParameterName = paramName;
  42. param.MySqlDbType = dbType;
  43. param.Value = paramValue;
  44. cmd.Parameters.Add(param);
  45. return cmd;
  46. }
  47. private static IList<T> MapToList<T>(this MySqlDataReader dr)
  48. {
  49. var objList = new List<T>();
  50. var props = typeof(T).GetRuntimeProperties();
  51. var columnSchema = dr.GetCustomColumnSchema();
  52. var colMapping = columnSchema//dr.GetColumnSchema()
  53. .Where(x => props.Any(y => y.Name.ToLower() == x.ColumnName.ToLower()))
  54. .ToDictionary(key => key.ColumnName.ToLower());
  55. if (dr.HasRows)
  56. {
  57. while (dr.Read())
  58. {
  59. T obj = Activator.CreateInstance<T>();
  60. foreach (var prop in props)
  61. {
  62. var mappedColumn = colMapping[prop.Name.ToLower()];
  63. var ordinal = colMapping[prop.Name.ToLower()].ColumnOrdinal.Value;
  64. var val = dr.GetValue(ordinal - 1);
  65. prop.SetValue(obj, val == DBNull.Value ? null : val);
  66. }
  67. objList.Add(obj);
  68. }
  69. }
  70. return objList;
  71. }
  72. public static int ExecuteStoredProc(this MySqlCommand command)
  73. {
  74. using (command)
  75. {
  76. try
  77. {
  78. if (command.Connection.State == ConnectionState.Closed)
  79. command.Connection.Open();
  80. return command.ExecuteNonQuery();
  81. }
  82. catch(MySqlException ex)
  83. {
  84. Console.WriteLine(ex.ToString());
  85. }
  86. finally
  87. {
  88. command.Connection.Close();
  89. }
  90. return -1;
  91. }
  92. }
  93. public static IList<T> ExecuteStoredProc<T>(this MySqlCommand command)
  94. {
  95. using (command)
  96. {
  97. try
  98. {
  99. if (command.Connection.State == ConnectionState.Closed)
  100. command.Connection.Open();
  101. using (MySqlDataReader reader = command.ExecuteReader())
  102. {
  103. return reader.MapToList<T>();
  104. }
  105. }
  106. catch(MySqlException ex)
  107. {
  108. Console.WriteLine(ex.ToString());
  109. }
  110. finally
  111. {
  112. command.Connection.Close();
  113. }
  114. return null;
  115. }
  116. }
  117. /// <summary>
  118. /// Custom column schema to support lack of native method.
  119. /// </summary>
  120. private static ReadOnlyCollection<DbColumn> GetCustomColumnSchema(this DbDataReader reader)
  121. {
  122. IList<DbColumn> columnSchema = new List<DbColumn>();
  123. DataTable schemaTable = reader.GetSchemaTable();
  124. DataColumnCollection schemaTableColumns = schemaTable.Columns;
  125. foreach (DataRow row in schemaTable.Rows)
  126. {
  127. DbColumn dbColumn = new DataRowDbColumn(row, schemaTableColumns);
  128. if (!columnSchema.Any(c => c.ColumnName == dbColumn.ColumnName))
  129. {
  130. columnSchema.Add(dbColumn);
  131. }
  132. }
  133. ReadOnlyCollection<DbColumn> readOnlyColumnSchema = new ReadOnlyCollection<DbColumn>(columnSchema);
  134. return readOnlyColumnSchema;
  135. }
  136. }
  137. internal class ColumnNameComparer : IEqualityComparer<string>
  138. {
  139. public bool Equals(string x, string y)
  140. {
  141. return x.Equals(y);
  142. }
  143. public int GetHashCode(string obj)
  144. {
  145. return obj.GetHashCode();
  146. }
  147. }
  148. }