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.

SqlServerManager.cs 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using iiie.Logs.DataAccess;
  7. using iiie.Logs.DBO;
  8. using System.Linq.Dynamic;
  9. namespace iiie.WebApiUtils.BusinessManager
  10. {
  11. /// <summary>
  12. /// Helper for SQL Server data access
  13. /// </summary>
  14. public abstract class SqlServerManager<TDbObject, TDbo, TEntities, TThis>
  15. where TDbObject : class
  16. where TEntities : DbContext, new()
  17. where TThis : SqlServerManager<TDbObject, TDbo, TEntities, TThis>, new()
  18. {
  19. private class DbObjectId
  20. {
  21. public long id { get; set; }
  22. }
  23. /// <summary>
  24. /// Return the table to be used
  25. /// </summary>
  26. /// <param name="db">The database</param>
  27. /// <returns>The table instance</returns>
  28. public abstract DbSet<TDbObject> GetTable(TEntities db);
  29. public abstract TDbo DbToDbo(TDbObject obj);
  30. public abstract TDbObject DboToDb(TDbo obj);
  31. /// <summary>
  32. /// Return the database table to use
  33. /// </summary>
  34. /// <param name="db">The database instance</param>
  35. /// <returns>The table</returns>
  36. public static DbSet<TDbObject> GetTableStatic(TEntities db)
  37. {
  38. var type = new TThis();
  39. return type.GetTable(db);
  40. }
  41. /// <summary>
  42. /// Helper to convert DB object to DBO
  43. /// </summary>
  44. /// <param name="res">The result to convert</param>
  45. /// <returns>The DBO object</returns>
  46. public static OpResult<TDbo> DbToDboStatic(OpResult<TDbObject> res)
  47. {
  48. if (!res)
  49. return OpResult<TDbo>.Error(res);
  50. var obj = new TThis();
  51. return OpResult<TDbo>.Ok(obj.DbToDbo(res.Data));
  52. }
  53. /// <summary>
  54. /// Helper to convert DBO object to DB
  55. /// </summary>
  56. /// <param name="res">The result to convert</param>
  57. /// <returns>The DB object</returns>
  58. public static OpResult<TDbObject> DboToDbStatic(OpResult<TDbo> res)
  59. {
  60. if (!res)
  61. return OpResult<TDbObject>.Error(res);
  62. var obj = new TThis();
  63. return OpResult<TDbObject>.Ok(obj.DboToDb(res.Data));
  64. }
  65. /// <summary>
  66. /// Helper to convert DB object to DBO
  67. /// </summary>
  68. /// <param name="res">The result to convert</param>
  69. /// <returns>The DBO object</returns>
  70. public static TDbo DbToDboStatic(TDbObject res)
  71. {
  72. var obj = new TThis();
  73. return obj.DbToDbo(res);
  74. }
  75. /// <summary>
  76. /// Helper to convert DBO object to DB
  77. /// </summary>
  78. /// <param name="res">The result to convert</param>
  79. /// <returns>The DB object</returns>
  80. public static TDbObject DboToDbStatic(TDbo res)
  81. {
  82. var obj = new TThis();
  83. return obj.DboToDb(res);
  84. }
  85. /// <summary>
  86. /// Execute SQL quries in try catch
  87. /// </summary>
  88. /// <param name="func">The queries to be performed</param>
  89. /// <returns>The result or an error</returns>
  90. public static OpResult<U> Execute<U>(Func<TEntities, DbSet<TDbObject>, OpResult<U>> func)
  91. {
  92. try
  93. {
  94. using (var db = new TEntities())
  95. {
  96. var table = GetTableStatic(db);
  97. return func(db, table);
  98. }
  99. }
  100. catch (Exception e)
  101. {
  102. return Logger.Error<U>(ResultStatus.DBError, e);
  103. }
  104. }
  105. /// <summary>
  106. /// Get a single DB object matching the predicate
  107. /// </summary>
  108. /// <param name="predicate">The predicate</param>
  109. /// <returns>The object that match, or null</returns>
  110. public static OpResult<TDbObject> GetSingle(Expression<Func<TDbObject, bool>> predicate)
  111. {
  112. return Execute((db, table) =>
  113. {
  114. var o = table.FirstOrDefault(predicate);
  115. if (o == null)
  116. {
  117. return OpResult<TDbObject>.Error(ResultStatus.NotFound, typeof(TThis).Name + ": Value not found", "");
  118. }
  119. return OpResult<TDbObject>.Ok(o);
  120. });
  121. }
  122. /// <summary>
  123. /// Get a single DBO matching the predicate
  124. /// </summary>
  125. /// <param name="predicate">The predicate</param>
  126. /// <returns>The object that match, or null</returns>
  127. public static OpResult<TDbo> GetSingleDbo(Expression<Func<TDbObject, bool>> predicate)
  128. {
  129. return DbToDboStatic(GetSingle(predicate));
  130. }
  131. /// <summary>
  132. /// Get all DB object matching the predicate
  133. /// </summary>
  134. /// <param name="predicate">The predicate</param>
  135. /// <returns>All matching objects</returns>
  136. public static OpResult<IEnumerable<TDbObject>> GetMultiple(Expression<Func<TDbObject, bool>> predicate)
  137. {
  138. return Execute((db, table) => OpResult<IEnumerable<TDbObject>>.Ok(table.Where(predicate).ToList()));
  139. }
  140. /// <summary>
  141. /// Get all DBO matching the predicate
  142. /// </summary>
  143. /// <typeparam name="TDbo">The DBO type</typeparam>
  144. /// <param name="predicate">The predicate</param>
  145. /// <returns>All matching objects</returns>
  146. public static OpResult<IEnumerable<TDbo>> GetMultipleDbo(Expression<Func<TDbObject, bool>> predicate)
  147. {
  148. var res = GetMultiple(predicate);
  149. if (!res)
  150. return OpResult<IEnumerable<TDbo>>.Error(res);
  151. var dbo = res.Data.Select(DbToDboStatic);
  152. return OpResult<IEnumerable<TDbo>>.Ok(dbo);
  153. }
  154. /// <summary>
  155. /// Add an entry in the database
  156. /// </summary>
  157. /// <param name="obj">The object to be added</param>
  158. /// <returns>Always true or an OpResult error</returns>
  159. public static OpResult<bool> Add(TDbObject obj)
  160. {
  161. return Execute((db, table) =>
  162. {
  163. table.Add(obj);
  164. db.SaveChanges();
  165. return OpResult<bool>.Ok(true);
  166. });
  167. }
  168. /// <summary>
  169. /// Add an entry in the database
  170. /// </summary>
  171. /// <param name="obj"></param>
  172. /// <returns>Always true or an OpResult error</returns>
  173. public static OpResult<bool> AddDbo(TDbo obj)
  174. {
  175. return Add(DboToDbStatic(obj));
  176. }
  177. /// <summary>
  178. /// Get an object by its primary key(s)
  179. /// </summary>
  180. /// <param name="pairs">The key names and values</param>
  181. /// <returns>The object</returns>
  182. public static OpResult<TDbObject> GetByPrimary(params KeyValuePair<string, object>[] pairs)
  183. {
  184. var param = Expression.Parameter(typeof(TDbObject), "x");
  185. Expression totalExp = null;
  186. foreach (var pair in pairs)
  187. {
  188. var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
  189. totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
  190. }
  191. var lambda = Expression.Lambda<Func<TDbObject, bool>>(totalExp, param);
  192. return GetSingle(lambda);
  193. }
  194. /// <summary>
  195. /// Get an object by its id
  196. /// </summary>
  197. /// <param name="id">The id of the object</param>
  198. /// <returns>The object</returns>
  199. public static OpResult<TDbObject> GetById(long id)
  200. {
  201. return GetByPrimary(new KeyValuePair<string, object>("id", id));
  202. }
  203. /// <summary>
  204. /// Get an object by its id
  205. /// </summary>
  206. /// <param name="id">The id of the object</param>
  207. /// <returns>The object</returns>
  208. public static OpResult<TDbo> GetByIdDbo(long id)
  209. {
  210. return DbToDboStatic(GetById(id));
  211. }
  212. }
  213. }