SqlServerDatabase.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Microsoft.EntityFrameworkCore;
  11. using Microsoft.EntityFrameworkCore.Metadata;
  12. using Microsoft.EntityFrameworkCore.Storage;
  13. using YiSha.Util.Extension;
  14. namespace YiSha.Data.EF
  15. {
  16. public class SqlServerDatabase : IDatabase
  17. {
  18. #region 构造函数
  19. /// <summary>
  20. /// 构造方法
  21. /// </summary>
  22. public SqlServerDatabase(string connString)
  23. {
  24. dbContext = new SqlServerDbContext(connString);
  25. }
  26. #endregion
  27. #region 属性
  28. /// <summary>
  29. /// 获取 当前使用的数据访问上下文对象
  30. /// </summary>
  31. public DbContext dbContext { get; set; }
  32. /// <summary>
  33. /// 事务对象
  34. /// </summary>
  35. public IDbContextTransaction dbContextTransaction { get; set; }
  36. #endregion
  37. #region 事务提交
  38. /// <summary>
  39. /// 事务开始
  40. /// </summary>
  41. /// <returns></returns>
  42. public async Task<IDatabase> BeginTrans()
  43. {
  44. DbConnection dbConnection = dbContext.Database.GetDbConnection();
  45. if (dbConnection.State == ConnectionState.Closed)
  46. {
  47. await dbConnection.OpenAsync();
  48. }
  49. dbContextTransaction = await dbContext.Database.BeginTransactionAsync();
  50. return this;
  51. }
  52. /// <summary>
  53. /// 提交当前操作的结果
  54. /// </summary>
  55. public async Task<int> CommitTrans()
  56. {
  57. try
  58. {
  59. DbContextExtension.SetEntityDefaultValue(dbContext);
  60. int returnValue = await dbContext.SaveChangesAsync();
  61. if (dbContextTransaction != null)
  62. {
  63. await dbContextTransaction.CommitAsync();
  64. await this.Close();
  65. }
  66. else
  67. {
  68. await this.Close();
  69. }
  70. return returnValue;
  71. }
  72. catch
  73. {
  74. throw;
  75. }
  76. finally
  77. {
  78. if (dbContextTransaction == null)
  79. {
  80. await this.Close();
  81. }
  82. }
  83. }
  84. /// <summary>
  85. /// 把当前操作回滚成未提交状态
  86. /// </summary>
  87. public async Task RollbackTrans()
  88. {
  89. await this.dbContextTransaction.RollbackAsync();
  90. await this.dbContextTransaction.DisposeAsync();
  91. await this.Close();
  92. }
  93. /// <summary>
  94. /// 关闭连接 内存回收
  95. /// </summary>
  96. public async Task Close()
  97. {
  98. await dbContext.DisposeAsync();
  99. }
  100. #endregion
  101. #region 执行 SQL 语句
  102. public async Task<int> ExecuteBySql(string strSql)
  103. {
  104. if (dbContextTransaction == null)
  105. {
  106. return await dbContext.Database.ExecuteSqlRawAsync(strSql);
  107. }
  108. else
  109. {
  110. await dbContext.Database.ExecuteSqlRawAsync(strSql);
  111. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  112. }
  113. }
  114. public async Task<int> ExecuteBySql(string strSql, params DbParameter[] dbParameter)
  115. {
  116. if (dbContextTransaction == null)
  117. {
  118. return await dbContext.Database.ExecuteSqlRawAsync(strSql, dbParameter);
  119. }
  120. else
  121. {
  122. await dbContext.Database.ExecuteSqlRawAsync(strSql, dbParameter);
  123. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  124. }
  125. }
  126. public async Task<int> ExecuteByProc(string procName)
  127. {
  128. if (dbContextTransaction == null)
  129. {
  130. return await dbContext.Database.ExecuteSqlRawAsync(DbContextExtension.BuilderProc(procName));
  131. }
  132. else
  133. {
  134. await dbContext.Database.ExecuteSqlRawAsync(DbContextExtension.BuilderProc(procName));
  135. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  136. }
  137. }
  138. public async Task<int> ExecuteByProc(string procName, params DbParameter[] dbParameter)
  139. {
  140. if (dbContextTransaction == null)
  141. {
  142. return await dbContext.Database.ExecuteSqlRawAsync(DbContextExtension.BuilderProc(procName, dbParameter), dbParameter);
  143. }
  144. else
  145. {
  146. await dbContext.Database.ExecuteSqlRawAsync(DbContextExtension.BuilderProc(procName, dbParameter), dbParameter);
  147. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  148. }
  149. }
  150. #endregion
  151. #region 对象实体 添加、修改、删除
  152. public async Task<int> Insert<T>(T entity) where T : class
  153. {
  154. dbContext.Entry<T>(entity).State = EntityState.Added;
  155. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  156. }
  157. public async Task<int> Insert<T>(IEnumerable<T> entities) where T : class
  158. {
  159. foreach (var entity in entities)
  160. {
  161. dbContext.Entry<T>(entity).State = EntityState.Added;
  162. }
  163. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  164. }
  165. public async Task<int> Delete<T>() where T : class
  166. {
  167. IEntityType entityType = DbContextExtension.GetEntityType<T>(dbContext);
  168. if (entityType != null)
  169. {
  170. string tableName = entityType.GetTableName();
  171. return await this.ExecuteBySql(DbContextExtension.DeleteSql(tableName));
  172. }
  173. return -1;
  174. }
  175. public async Task<int> Delete<T>(T entity) where T : class
  176. {
  177. dbContext.Set<T>().Attach(entity);
  178. dbContext.Set<T>().Remove(entity);
  179. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  180. }
  181. public async Task<int> Delete<T>(IEnumerable<T> entities) where T : class
  182. {
  183. foreach (var entity in entities)
  184. {
  185. dbContext.Set<T>().Attach(entity);
  186. dbContext.Set<T>().Remove(entity);
  187. }
  188. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  189. }
  190. public async Task<int> Delete<T>(Expression<Func<T, bool>> condition) where T : class, new()
  191. {
  192. IEnumerable<T> entities = await dbContext.Set<T>().Where(condition).ToListAsync();
  193. return entities.Count() > 0 ? await Delete(entities) : 0;
  194. }
  195. public async Task<int> Delete<T>(string keyValue) where T : class
  196. {
  197. IEntityType entityType = DbContextExtension.GetEntityType<T>(dbContext);
  198. if (entityType != null)
  199. {
  200. string tableName = entityType.GetTableName();
  201. string keyField = "Id";
  202. return await this.ExecuteBySql(DbContextExtension.DeleteSql(tableName, keyField, keyValue));
  203. }
  204. return -1;
  205. }
  206. public async Task<int> Delete<T>(string[] keyValue) where T : class
  207. {
  208. IEntityType entityType = DbContextExtension.GetEntityType<T>(dbContext);
  209. if (entityType != null)
  210. {
  211. string tableName = entityType.GetTableName();
  212. string keyField = "Id";
  213. return await this.ExecuteBySql(DbContextExtension.DeleteSql(tableName, keyField, keyValue));
  214. }
  215. return -1;
  216. }
  217. public async Task<int> Delete<T>(string propertyName, string propertyValue) where T : class
  218. {
  219. IEntityType entityType = DbContextExtension.GetEntityType<T>(dbContext);
  220. if (entityType != null)
  221. {
  222. string tableName = entityType.GetTableName();
  223. return await this.ExecuteBySql(DbContextExtension.DeleteSql(tableName, propertyName, propertyValue));
  224. }
  225. return -1;
  226. }
  227. public async Task<int> Update<T>(T entity) where T : class
  228. {
  229. dbContext.Set<T>().Attach(entity);
  230. Hashtable props = DatabasesExtension.GetPropertyInfo<T>(entity);
  231. foreach (string item in props.Keys)
  232. {
  233. if (item == "Id")
  234. {
  235. continue;
  236. }
  237. object value = dbContext.Entry(entity).Property(item).CurrentValue;
  238. if (value != null)
  239. {
  240. dbContext.Entry(entity).Property(item).IsModified = true;
  241. }
  242. }
  243. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  244. }
  245. public async Task<int> Update<T>(IEnumerable<T> entities) where T : class
  246. {
  247. foreach (var entity in entities)
  248. {
  249. dbContext.Entry<T>(entity).State = EntityState.Modified;
  250. }
  251. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  252. }
  253. public async Task<int> UpdateAllField<T>(T entity) where T : class
  254. {
  255. dbContext.Set<T>().Attach(entity);
  256. dbContext.Entry(entity).State = EntityState.Modified;
  257. return dbContextTransaction == null ? await this.CommitTrans() : 0;
  258. }
  259. public async Task<int> Update<T>(Expression<Func<T, bool>> condition) where T : class, new()
  260. {
  261. IEnumerable<T> entities = await dbContext.Set<T>().Where(condition).ToListAsync();
  262. return entities.Count() > 0 ? await Update(entities) : 0;
  263. }
  264. public IQueryable<T> IQueryable<T>(Expression<Func<T, bool>> condition) where T : class, new()
  265. {
  266. return dbContext.Set<T>().Where(condition);
  267. }
  268. #endregion
  269. #region 对象实体 查询
  270. public async Task<T> FindEntity<T>(object keyValue) where T : class
  271. {
  272. return await dbContext.Set<T>().FindAsync(keyValue);
  273. }
  274. public async Task<T> FindEntity<T>(Expression<Func<T, bool>> condition) where T : class, new()
  275. {
  276. return await dbContext.Set<T>().Where(condition).FirstOrDefaultAsync();
  277. }
  278. public async Task<IEnumerable<T>> FindList<T>() where T : class, new()
  279. {
  280. return await dbContext.Set<T>().ToListAsync();
  281. }
  282. public async Task<IEnumerable<T>> FindList<T>(Func<T, object> orderby) where T : class, new()
  283. {
  284. var list = await dbContext.Set<T>().ToListAsync();
  285. list = list.OrderBy(orderby).ToList();
  286. return list;
  287. }
  288. public async Task<IEnumerable<T>> FindList<T>(Expression<Func<T, bool>> condition) where T : class, new()
  289. {
  290. return await dbContext.Set<T>().Where(condition).ToListAsync();
  291. }
  292. public async Task<IEnumerable<T>> FindList<T>(string strSql) where T : class
  293. {
  294. return await FindList<T>(strSql, null);
  295. }
  296. public async Task<IEnumerable<T>> FindList<T>(string strSql, DbParameter[] dbParameter) where T : class
  297. {
  298. using (var dbConnection = dbContext.Database.GetDbConnection())
  299. {
  300. var reader = await new DbHelper(dbContext, dbConnection).ExecuteReadeAsync(CommandType.Text, strSql, dbParameter);
  301. return DatabasesExtension.IDataReaderToList<T>(reader);
  302. }
  303. }
  304. public async Task<(int total, IEnumerable<T> list)> FindList<T>(string sort, bool isAsc, int pageSize, int pageIndex) where T : class, new()
  305. {
  306. var tempData = dbContext.Set<T>().AsQueryable();
  307. return await FindList<T>(tempData, sort, isAsc, pageSize, pageIndex);
  308. }
  309. public async Task<(int total, IEnumerable<T> list)> FindList<T>(Expression<Func<T, bool>> condition, string sort, bool isAsc, int pageSize, int pageIndex) where T : class, new()
  310. {
  311. var tempData = dbContext.Set<T>().Where(condition);
  312. return await FindList<T>(tempData, sort, isAsc, pageSize, pageIndex);
  313. }
  314. public async Task<(int total, IEnumerable<T>)> FindList<T>(string strSql, string sort, bool isAsc, int pageSize, int pageIndex) where T : class
  315. {
  316. return await FindList<T>(strSql, null, sort, isAsc, pageSize, pageIndex);
  317. }
  318. public async Task<(int total, IEnumerable<T>)> FindList<T>(string strSql, DbParameter[] dbParameter, string sort, bool isAsc, int pageSize, int pageIndex) where T : class
  319. {
  320. using (var dbConnection = dbContext.Database.GetDbConnection())
  321. {
  322. DbHelper dbHelper = new DbHelper(dbContext, dbConnection);
  323. StringBuilder sb = new StringBuilder();
  324. sb.Append(DatabasePageExtension.SqlServerPageSql(strSql, dbParameter, sort, isAsc, pageSize, pageIndex));
  325. object tempTotal = await dbHelper.ExecuteScalarAsync(CommandType.Text, "SELECT COUNT(1) FROM (" + strSql + ") T", dbParameter);
  326. int total = tempTotal.ParseToInt();
  327. if (total > 0)
  328. {
  329. var reader = await dbHelper.ExecuteReadeAsync(CommandType.Text, sb.ToString(), dbParameter);
  330. return (total, DatabasesExtension.IDataReaderToList<T>(reader));
  331. }
  332. else
  333. {
  334. return (total, new List<T>());
  335. }
  336. }
  337. }
  338. private async Task<(int total, IEnumerable<T> list)> FindList<T>(IQueryable<T> tempData, string sort, bool isAsc, int pageSize, int pageIndex)
  339. {
  340. tempData = DatabasesExtension.AppendSort<T>(tempData, sort, isAsc);
  341. var total = tempData.Count();
  342. if (total > 0)
  343. {
  344. tempData = tempData.Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize).AsQueryable();
  345. var list = await tempData.ToListAsync();
  346. return (total, list);
  347. }
  348. else
  349. {
  350. return (total, new List<T>());
  351. }
  352. }
  353. #endregion
  354. #region 数据源查询
  355. public async Task<DataTable> FindTable(string strSql)
  356. {
  357. return await FindTable(strSql, null);
  358. }
  359. public async Task<DataTable> FindTable(string strSql, DbParameter[] dbParameter)
  360. {
  361. using (var dbConnection = dbContext.Database.GetDbConnection())
  362. {
  363. var reader = await new DbHelper(dbContext, dbConnection).ExecuteReadeAsync(CommandType.Text, strSql, dbParameter);
  364. return DatabasesExtension.IDataReaderToDataTable(reader);
  365. }
  366. }
  367. public async Task<(int total, DataTable)> FindTable(string strSql, string sort, bool isAsc, int pageSize, int pageIndex)
  368. {
  369. return await FindTable(strSql, null, sort, isAsc, pageSize, pageIndex);
  370. }
  371. public async Task<(int total, DataTable)> FindTable(string strSql, DbParameter[] dbParameter, string sort, bool isAsc, int pageSize, int pageIndex)
  372. {
  373. using (var dbConnection = dbContext.Database.GetDbConnection())
  374. {
  375. DbHelper dbHelper = new DbHelper(dbContext, dbConnection);
  376. StringBuilder sb = new StringBuilder();
  377. sb.Append(DatabasePageExtension.SqlServerPageSql(strSql, dbParameter, sort, isAsc, pageSize, pageIndex));
  378. object tempTotal = await dbHelper.ExecuteScalarAsync(CommandType.Text, "SELECT COUNT(1) FROM (" + strSql + ") T", dbParameter);
  379. int total = tempTotal.ParseToInt();
  380. if (total > 0)
  381. {
  382. var reader = await dbHelper.ExecuteReadeAsync(CommandType.Text, sb.ToString(), dbParameter);
  383. DataTable resultTable = DatabasesExtension.IDataReaderToDataTable(reader);
  384. return (total, resultTable);
  385. }
  386. else
  387. {
  388. return (total, new DataTable());
  389. }
  390. }
  391. }
  392. public async Task<object> FindObject(string strSql)
  393. {
  394. return await FindObject(strSql, null);
  395. }
  396. public async Task<object> FindObject(string strSql, DbParameter[] dbParameter)
  397. {
  398. using (var dbConnection = dbContext.Database.GetDbConnection())
  399. {
  400. return await new DbHelper(dbContext, dbConnection).ExecuteScalarAsync(CommandType.Text, strSql, dbParameter);
  401. }
  402. }
  403. public async Task<T> FindObject<T>(string strSql, DbParameter[] dbParameter = null) where T : class
  404. {
  405. var list = await dbContext.SqlQuery<T>(strSql, dbParameter);
  406. return list.FirstOrDefault();
  407. }
  408. #endregion
  409. }
  410. }