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.

Database.cs 41 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. using Dapper;
  2. using Learun.Util;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.Data;
  8. using System.Data.Common;
  9. using System.Data.Entity;
  10. using System.Data.SqlClient;
  11. using System.Linq;
  12. using System.Linq.Expressions;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Threading.Tasks;
  16. namespace Learun.DataBase.SqlServer
  17. {
  18. /// <summary>
  19. /// 版 本 Learun-ADMS-Ultimate V7.0.0 数字化智慧校园
  20. /// Copyright (c) 2013-2018 北京泉江科技有限公司
  21. /// 创建人:陈彬彬(Learun智慧校园数据库小组)
  22. /// 日 期:2017.03.04
  23. /// 描 述:数据库操作类
  24. /// </summary>
  25. public class Database : IDatabase
  26. {
  27. #region 构造函数
  28. ///// <summary>
  29. ///// 构造方法
  30. ///// </summary>
  31. public Database(string connString)
  32. {
  33. var obj = ConfigurationManager.ConnectionStrings[connString];
  34. string connectionString = obj == null ? connString : obj.ConnectionString;
  35. dbcontext = new DatabaseContext(connectionString);
  36. }
  37. #endregion
  38. #region 属性
  39. /// <summary>
  40. /// 获取 当前使用的数据访问上下文对象
  41. /// </summary>
  42. public DbContext dbcontext { get; set; }
  43. /// <summary>
  44. /// 事务对象
  45. /// </summary>
  46. public DbTransaction dbTransaction { get; set; }
  47. /// <summary>
  48. /// 获取连接上下文
  49. /// </summary>
  50. /// <returns></returns>
  51. public DbConnection getDbConnection()
  52. {
  53. return dbcontext.Database.Connection;
  54. }
  55. #endregion
  56. #region 事物提交
  57. /// <summary>
  58. /// 事务开始
  59. /// </summary>
  60. /// <returns></returns>
  61. public IDatabase BeginTrans()
  62. {
  63. if (dbcontext.Database.Connection.State == ConnectionState.Closed)
  64. {
  65. dbcontext.Database.Connection.Open();
  66. }
  67. dbTransaction = dbcontext.Database.Connection.BeginTransaction();
  68. dbcontext.Database.UseTransaction(dbTransaction);
  69. return this;
  70. }
  71. public async Task<int> CommitAsync()
  72. {
  73. try
  74. {
  75. int returnValue = await dbcontext.SaveChangesAsync();
  76. if (dbTransaction != null)
  77. {
  78. dbTransaction.Commit();
  79. this.Close();
  80. }
  81. return returnValue;
  82. }
  83. catch (Exception ex)
  84. {
  85. if (ex.InnerException != null && ex.InnerException.InnerException is SqlException)
  86. {
  87. SqlException sqlEx = ex.InnerException.InnerException as SqlException;
  88. throw ExceptionEx.ThrowDataAccessException(sqlEx, sqlEx.Message);
  89. }
  90. throw;
  91. }
  92. finally
  93. {
  94. if (dbTransaction == null)
  95. {
  96. this.Close();
  97. }
  98. }
  99. }
  100. /// <summary>
  101. /// 提交当前操作的结果
  102. /// </summary>
  103. public int Commit()
  104. {
  105. try
  106. {
  107. int returnValue = dbcontext.SaveChanges();
  108. if (dbTransaction != null)
  109. {
  110. dbTransaction.Commit();
  111. this.Close();
  112. }
  113. return returnValue;
  114. }
  115. catch (Exception ex)
  116. {
  117. if (ex.InnerException != null && ex.InnerException.InnerException is SqlException)
  118. {
  119. SqlException sqlEx = ex.InnerException.InnerException as SqlException;
  120. throw ExceptionEx.ThrowDataAccessException(sqlEx, sqlEx.Message);
  121. }
  122. throw;
  123. }
  124. finally
  125. {
  126. if (dbTransaction == null)
  127. {
  128. this.Close();
  129. }
  130. }
  131. }
  132. /// <summary>
  133. /// 把当前操作回滚成未提交状态
  134. /// </summary>
  135. public void Rollback()
  136. {
  137. this.dbTransaction.Rollback();
  138. this.dbTransaction.Dispose();
  139. this.Close();
  140. }
  141. /// <summary>
  142. /// 关闭连接 内存回收
  143. /// </summary>
  144. public void Close()
  145. {
  146. dbcontext.Dispose();
  147. }
  148. #endregion
  149. #region 执行 SQL 语句
  150. public async Task<int> ExecuteAsyncBySql(string strSql)
  151. {
  152. try
  153. {
  154. return await dbcontext.Database.Connection.ExecuteAsync(strSql, null, dbTransaction);
  155. }
  156. catch (Exception)
  157. {
  158. throw;
  159. }
  160. finally
  161. {
  162. if (dbTransaction == null)
  163. {
  164. this.Close();
  165. }
  166. }
  167. }
  168. /// <summary>
  169. /// 执行sql语句
  170. /// </summary>
  171. /// <param name="strSql">sql语句</param>
  172. /// <returns></returns>
  173. public int ExecuteBySql(string strSql)
  174. {
  175. try
  176. {
  177. return dbcontext.Database.Connection.Execute(strSql, null, dbTransaction);
  178. }
  179. catch (Exception)
  180. {
  181. throw;
  182. }
  183. finally
  184. {
  185. if (dbTransaction == null)
  186. {
  187. this.Close();
  188. }
  189. }
  190. }
  191. /// <summary>
  192. /// 执行sql语句(带参数)
  193. /// </summary>
  194. /// <param name="strSql">sql语句</param>
  195. /// <param name="dbParameter">参数</param>
  196. /// <returns></returns>
  197. public int ExecuteBySql(string strSql, object dbParameter)
  198. {
  199. try
  200. {
  201. return dbcontext.Database.Connection.Execute(strSql, dbParameter, dbTransaction);
  202. }
  203. catch (Exception)
  204. {
  205. throw;
  206. }
  207. finally
  208. {
  209. if (dbTransaction == null)
  210. {
  211. this.Close();
  212. }
  213. }
  214. }
  215. /// <summary>
  216. /// 执行存储过程
  217. /// </summary>
  218. /// <param name="procName">存储过程名称</param>
  219. /// <returns></returns>
  220. public int ExecuteByProc(string procName)
  221. {
  222. try
  223. {
  224. return dbcontext.Database.Connection.Execute(procName, null, dbTransaction, null, CommandType.StoredProcedure);
  225. }
  226. catch (Exception)
  227. {
  228. throw;
  229. }
  230. finally
  231. {
  232. if (dbTransaction == null)
  233. {
  234. this.Close();
  235. }
  236. }
  237. }
  238. /// <summary>
  239. /// 执行存储过程
  240. /// </summary>
  241. /// <param name="procName">存储过程名称</param>
  242. /// <param name="dbParameter">参数</param>
  243. /// <returns></returns>
  244. public int ExecuteByProc(string procName, object dbParameter)
  245. {
  246. try
  247. {
  248. return dbcontext.Database.Connection.Execute(procName, dbParameter, dbTransaction, null, CommandType.StoredProcedure);
  249. }
  250. catch (Exception)
  251. {
  252. throw;
  253. }
  254. finally
  255. {
  256. if (dbTransaction == null)
  257. {
  258. this.Close();
  259. }
  260. }
  261. }
  262. /// <summary>
  263. /// 执行存储过程
  264. /// </summary>
  265. /// <param name="procName">存储过程名称</param>
  266. /// <returns></returns>
  267. public T ExecuteByProc<T>(string procName) where T : class
  268. {
  269. try
  270. {
  271. return dbcontext.Database.Connection.ExecuteScalar<T>(procName, null, dbTransaction, null, CommandType.StoredProcedure);
  272. }
  273. catch (Exception)
  274. {
  275. throw;
  276. }
  277. finally
  278. {
  279. if (dbTransaction == null)
  280. {
  281. this.Close();
  282. }
  283. }
  284. }
  285. /// <summary>
  286. /// 执行存储过程
  287. /// </summary>
  288. /// <param name="procName">存储过程名称</param>
  289. /// <param name="dbParameter">参数</param>
  290. /// <returns></returns>
  291. public T ExecuteByProc<T>(string procName, object dbParameter) where T : class
  292. {
  293. try
  294. {
  295. return dbcontext.Database.Connection.ExecuteScalar<T>(procName, dbParameter, dbTransaction, null, CommandType.StoredProcedure);
  296. }
  297. catch (Exception)
  298. {
  299. throw;
  300. }
  301. finally
  302. {
  303. if (dbTransaction == null)
  304. {
  305. this.Close();
  306. }
  307. }
  308. }
  309. /// <summary>
  310. /// 执行存储过程
  311. /// </summary>
  312. /// <param name="procName">存储过程名称</param>
  313. /// <returns></returns>
  314. public IEnumerable<T> QueryByProc<T>(string procName) where T : class
  315. {
  316. try
  317. {
  318. return dbcontext.Database.Connection.Query<T>(procName, null, dbTransaction, true, null, CommandType.StoredProcedure);
  319. }
  320. catch (Exception)
  321. {
  322. throw;
  323. }
  324. finally
  325. {
  326. if (dbTransaction == null)
  327. {
  328. this.Close();
  329. }
  330. }
  331. }
  332. /// <summary>
  333. /// 执行存储过程
  334. /// </summary>
  335. /// <param name="procName">存储过程名称</param>
  336. /// <param name="dbParameter">参数</param>
  337. /// <returns></returns>
  338. public IEnumerable<T> QueryByProc<T>(string procName, object dbParameter) where T : class
  339. {
  340. try
  341. {
  342. return dbcontext.Database.Connection.Query<T>(procName, dbParameter, dbTransaction, true, null, CommandType.StoredProcedure);
  343. }
  344. catch (Exception)
  345. {
  346. throw;
  347. }
  348. finally
  349. {
  350. if (dbTransaction == null)
  351. {
  352. this.Close();
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// 执行存储过程(获取集)
  358. /// </summary>
  359. /// <param name="procName">存储过程名称</param>
  360. /// <param name="dbParameter">参数</param>
  361. /// <returns></returns>
  362. public DataTable FindTableByProc(string procName, object dbParameter)
  363. {
  364. try
  365. {
  366. var IDataReader = dbcontext.Database.Connection.ExecuteReader(procName, dbParameter, dbTransaction, null, CommandType.StoredProcedure);
  367. return SqlHelper.IDataReaderToDataTable(IDataReader);
  368. }
  369. catch (Exception)
  370. {
  371. throw;
  372. }
  373. finally
  374. {
  375. if (dbTransaction == null)
  376. {
  377. this.Close();
  378. }
  379. }
  380. }
  381. #endregion
  382. #region 对象实体 添加、修改、删除
  383. /// <summary>
  384. /// 插入实体数据
  385. /// </summary>
  386. /// <typeparam name="T">类型</typeparam>
  387. /// <param name="entity">实体数据</param>
  388. /// <returns></returns>
  389. public int Insert<T>(T entity) where T : class
  390. {
  391. dbcontext.Entry<T>(entity).State = EntityState.Added;
  392. return dbTransaction == null ? this.Commit() : 0;
  393. }
  394. public async Task<int> InsertAsync<T>(IEnumerable<T> entities) where T : class
  395. {
  396. foreach (var entity in entities)
  397. {
  398. dbcontext.Entry<T>(entity).State = EntityState.Added;
  399. }
  400. return dbTransaction == null ? await this.CommitAsync() : 0;
  401. }
  402. /// <summary>
  403. /// 批量插入实体数据
  404. /// </summary>
  405. /// <typeparam name="T">类型</typeparam>
  406. /// <param name="entities">实体数据列表</param>
  407. /// <returns></returns>
  408. public int Insert<T>(IEnumerable<T> entities) where T : class
  409. {
  410. foreach (var entity in entities)
  411. {
  412. dbcontext.Entry<T>(entity).State = EntityState.Added;
  413. }
  414. return dbTransaction == null ? this.Commit() : 0;
  415. }
  416. /// <summary>
  417. /// 删除实体数据
  418. /// </summary>
  419. /// <typeparam name="T">类型</typeparam>
  420. /// <param name="entity">实体数据(需要主键赋值)</param>
  421. /// <returns></returns>
  422. public int Delete<T>(T entity) where T : class
  423. {
  424. dbcontext.Set<T>().Attach(entity);
  425. dbcontext.Set<T>().Remove(entity);
  426. return dbTransaction == null ? this.Commit() : 0;
  427. }
  428. /// <summary>
  429. /// 批量删除实体数据
  430. /// </summary>
  431. /// <typeparam name="T">类型</typeparam>
  432. /// <param name="entities">实体数据列表</param>
  433. /// <returns></returns>
  434. public int Delete<T>(IEnumerable<T> entities) where T : class
  435. {
  436. foreach (var entity in entities)
  437. {
  438. dbcontext.Set<T>().Attach(entity);
  439. dbcontext.Set<T>().Remove(entity);
  440. }
  441. return dbTransaction == null ? this.Commit() : 0;
  442. }
  443. /// <summary>
  444. /// 删除表数据(根据Lambda表达式)
  445. /// </summary>
  446. /// <typeparam name="T"></typeparam>
  447. /// <param name="condition"></param>
  448. /// <returns></returns>
  449. public int Delete<T>(Expression<Func<T, bool>> condition) where T : class, new()
  450. {
  451. IEnumerable<T> entities = dbcontext.Set<T>().Where(condition).ToList();
  452. return entities.Count() > 0 ? Delete(entities) : 0;
  453. }
  454. /// <summary>
  455. /// 更新实体数据
  456. /// </summary>
  457. /// <typeparam name="T">类型</typeparam>
  458. /// <param name="entity">实体数据</param>
  459. /// <returns></returns>
  460. public int Update<T>(T entity) where T : class
  461. {
  462. this.UpdateEntity(entity);
  463. return dbTransaction == null ? this.Commit() : 0;
  464. }
  465. /// <summary>
  466. /// 更新实体数据
  467. /// </summary>
  468. /// <typeparam name="T">类型</typeparam>
  469. /// <param name="entity">实体数据</param>
  470. /// <returns></returns>
  471. public int UpdateEx<T>(T entity) where T : class
  472. {
  473. dbcontext.Set<T>().Attach(entity);
  474. dbcontext.Entry(entity).State = EntityState.Modified;
  475. return dbTransaction == null ? this.Commit() : 0;
  476. }
  477. /// <summary>
  478. /// 批量更新实体数据
  479. /// </summary>
  480. /// <typeparam name="T">类型</typeparam>
  481. /// <param name="entities">实体数据列表</param>
  482. /// <returns></returns>
  483. public int Update<T>(IEnumerable<T> entities) where T : class
  484. {
  485. foreach (var entity in entities)
  486. {
  487. this.UpdateEntity(entity);
  488. }
  489. return dbTransaction == null ? this.Commit() : 0;
  490. }
  491. /// <summary>
  492. /// EF更新实体
  493. /// </summary>
  494. /// <typeparam name="T">类型</typeparam>
  495. /// <param name="entity">实体数据</param>
  496. private void UpdateEntity<T>(T entity) where T : class
  497. {
  498. dbcontext.Set<T>().Attach(entity);
  499. Hashtable props = SqlHelper.GetPropertyInfo<T>(entity);
  500. foreach (string item in props.Keys)
  501. {
  502. object value = dbcontext.Entry(entity).Property(item).CurrentValue;
  503. if (value != null)
  504. {
  505. if (value.ToString() == "&nbsp;")
  506. dbcontext.Entry(entity).Property(item).CurrentValue = null;
  507. dbcontext.Entry(entity).Property(item).IsModified = true;
  508. }
  509. }
  510. }
  511. #endregion
  512. #region 对象实体 查询
  513. public async Task<IEnumerable<T>> FindListAsync<T>(string strSql) where T : class
  514. {
  515. try
  516. {
  517. strSql = strSql.Replace("@", "?");
  518. return await dbcontext.Database.Connection.QueryAsync<T>(strSql, null, dbTransaction);
  519. }
  520. catch (Exception)
  521. {
  522. throw;
  523. }
  524. finally
  525. {
  526. if (dbTransaction == null)
  527. {
  528. this.Close();
  529. }
  530. }
  531. }
  532. public async Task<IEnumerable<T>> FindListAsync<T>(string strSql, object dbParameter) where T : class
  533. {
  534. try
  535. {
  536. strSql = strSql.Replace("@", "?");
  537. return await dbcontext.Database.Connection.QueryAsync<T>(strSql, dbParameter, dbTransaction);
  538. }
  539. catch (Exception)
  540. {
  541. throw;
  542. }
  543. finally
  544. {
  545. if (dbTransaction == null)
  546. {
  547. this.Close();
  548. }
  549. }
  550. }
  551. public async Task<IEnumerable<T>> FindListAsync<T>() where T : class, new()
  552. {
  553. try
  554. {
  555. return await dbcontext.Set<T>().ToListAsync();
  556. }
  557. catch (Exception)
  558. {
  559. throw;
  560. }
  561. finally
  562. {
  563. if (dbTransaction == null)
  564. {
  565. this.Close();
  566. }
  567. }
  568. }
  569. /// <summary>
  570. /// 查找一个实体根据主键
  571. /// </summary>
  572. /// <typeparam name="T">类型</typeparam>
  573. /// <param name="KeyValue">主键</param>
  574. /// <returns></returns>
  575. public T FindEntity<T>(object keyValue) where T : class
  576. {
  577. try
  578. {
  579. return dbcontext.Set<T>().Find(keyValue);
  580. }
  581. catch (Exception)
  582. {
  583. throw;
  584. }
  585. finally
  586. {
  587. if (dbTransaction == null)
  588. {
  589. this.Close();
  590. }
  591. }
  592. }
  593. /// <summary>
  594. /// 查找一个实体(根据表达式)
  595. /// </summary>
  596. /// <typeparam name="T">类型</typeparam>
  597. /// <param name="condition">表达式</param>
  598. /// <returns></returns>
  599. public T FindEntity<T>(Expression<Func<T, bool>> condition) where T : class, new()
  600. {
  601. try
  602. {
  603. return dbcontext.Set<T>().Where(condition).FirstOrDefault();
  604. }
  605. catch (Exception)
  606. {
  607. throw;
  608. }
  609. finally
  610. {
  611. if (dbTransaction == null)
  612. {
  613. this.Close();
  614. }
  615. }
  616. }
  617. /// <summary>
  618. /// 查找一个实体(根据sql)
  619. /// </summary>
  620. /// <typeparam name="T">类型</typeparam>
  621. /// <param name="strSql">sql语句</param>
  622. /// <param name="dbParameter">参数</param>
  623. /// <returns></returns>
  624. public T FindEntity<T>(string strSql, object dbParameter = null) where T : class, new()
  625. {
  626. try
  627. {
  628. var data = dbcontext.Database.Connection.Query<T>(strSql, dbParameter, dbTransaction);
  629. return data.FirstOrDefault();
  630. }
  631. catch (Exception)
  632. {
  633. throw;
  634. }
  635. finally
  636. {
  637. if (dbTransaction == null)
  638. {
  639. this.Close();
  640. }
  641. }
  642. }
  643. /// <summary>
  644. /// 获取IQueryable表达式
  645. /// </summary>
  646. /// <typeparam name="T">类型</typeparam>
  647. /// <returns></returns>
  648. public IQueryable<T> IQueryable<T>() where T : class, new()
  649. {
  650. try
  651. {
  652. return dbcontext.Set<T>();
  653. }
  654. catch (Exception)
  655. {
  656. throw;
  657. }
  658. finally
  659. {
  660. if (dbTransaction == null)
  661. {
  662. this.Close();
  663. }
  664. }
  665. }
  666. /// <summary>
  667. /// 获取IQueryable表达式(根据表达式)
  668. /// </summary>
  669. /// <typeparam name="T">类型</typeparam>
  670. /// <param name="condition">表达式</param>
  671. /// <returns></returns>
  672. public IQueryable<T> IQueryable<T>(Expression<Func<T, bool>> condition) where T : class, new()
  673. {
  674. try
  675. {
  676. return dbcontext.Set<T>().Where(condition);
  677. }
  678. catch (Exception)
  679. {
  680. throw;
  681. }
  682. finally
  683. {
  684. if (dbTransaction != null)
  685. {
  686. this.Close();
  687. }
  688. }
  689. }
  690. /// <summary>
  691. /// 查询列表(获取表所有数据)
  692. /// </summary>
  693. /// <typeparam name="T">类型</typeparam>
  694. /// <returns></returns>
  695. public IEnumerable<T> FindList<T>() where T : class, new()
  696. {
  697. try
  698. {
  699. return dbcontext.Set<T>().ToList();
  700. }
  701. catch (Exception)
  702. {
  703. throw;
  704. }
  705. finally
  706. {
  707. if (dbTransaction == null)
  708. {
  709. this.Close();
  710. }
  711. }
  712. }
  713. /// <summary>
  714. /// 查询列表(获取表所有数据)
  715. /// </summary>
  716. /// <typeparam name="T">类型</typeparam>
  717. /// <param name="orderby">排序</param>
  718. /// <returns></returns>
  719. public IEnumerable<T> FindList<T>(Func<T, object> orderby) where T : class, new()
  720. {
  721. try
  722. {
  723. return dbcontext.Set<T>().OrderBy(orderby).ToList();
  724. }
  725. catch (Exception)
  726. {
  727. throw;
  728. }
  729. finally
  730. {
  731. if (dbTransaction == null)
  732. {
  733. this.Close();
  734. }
  735. }
  736. }
  737. /// <summary>
  738. /// 查询列表根据表达式
  739. /// </summary>
  740. /// <typeparam name="T">类型</typeparam>
  741. /// <param name="condition">表达式</param>
  742. /// <returns></returns>
  743. public IEnumerable<T> FindList<T>(Expression<Func<T, bool>> condition) where T : class, new()
  744. {
  745. try
  746. {
  747. return dbcontext.Set<T>().Where(condition).ToList();
  748. }
  749. catch (Exception)
  750. {
  751. throw;
  752. }
  753. finally
  754. {
  755. if (dbTransaction == null)
  756. {
  757. this.Close();
  758. }
  759. }
  760. }
  761. /// <summary>
  762. /// 查询列表根据sql语句
  763. /// </summary>
  764. /// <typeparam name="T">类型</typeparam>
  765. /// <param name="strSql">sql语句</param>
  766. /// <returns></returns>
  767. public IEnumerable<T> FindList<T>(string strSql) where T : class
  768. {
  769. try
  770. {
  771. return dbcontext.Database.Connection.Query<T>(strSql, null, dbTransaction);
  772. }
  773. catch (Exception)
  774. {
  775. throw;
  776. }
  777. finally
  778. {
  779. if (dbTransaction == null)
  780. {
  781. this.Close();
  782. }
  783. }
  784. }
  785. /// <summary>
  786. /// 查询列表根据sql语句(带参数)
  787. /// </summary>
  788. /// <typeparam name="T">类型</typeparam>
  789. /// <param name="strSql">sql语句</param>
  790. /// <param name="dbParameter">参数</param>
  791. /// <returns></returns>
  792. public IEnumerable<T> FindList<T>(string strSql, object dbParameter) where T : class
  793. {
  794. try
  795. {
  796. return dbcontext.Database.Connection.Query<T>(strSql, dbParameter, dbTransaction);
  797. }
  798. catch (Exception)
  799. {
  800. throw;
  801. }
  802. finally
  803. {
  804. if (dbTransaction == null)
  805. {
  806. this.Close();
  807. }
  808. }
  809. }
  810. /// <summary>
  811. /// 查询列表(分页)
  812. /// </summary>
  813. /// <typeparam name="T">类型</typeparam>
  814. /// <param name="orderField">排序字段</param>
  815. /// <param name="isAsc">排序类型</param>
  816. /// <param name="pageSize">每页数据条数</param>
  817. /// <param name="pageIndex">页码</param>
  818. /// <param name="total">总共数据条数</param>
  819. /// <returns></returns>
  820. public IEnumerable<T> FindList<T>(string orderField, bool isAsc, int pageSize, int pageIndex, out int total) where T : class, new()
  821. {
  822. try
  823. {
  824. string[] _order = orderField.Split(',');
  825. MethodCallExpression resultExp = null;
  826. var tempData = dbcontext.Set<T>().AsQueryable();
  827. foreach (string item in _order)
  828. {
  829. if (!string.IsNullOrEmpty(item))
  830. {
  831. string _orderPart = item;
  832. _orderPart = Regex.Replace(_orderPart, @"\s+", " ");
  833. string[] _orderArry = _orderPart.Split(' ');
  834. string _orderField = _orderArry[0];
  835. bool sort = isAsc;
  836. if (_orderArry.Length == 2)
  837. {
  838. isAsc = _orderArry[1].ToUpper() == "ASC" ? true : false;
  839. }
  840. var parameter = Expression.Parameter(typeof(T), "t");
  841. var property = typeof(T).GetProperty(_orderField);
  842. var propertyAccess = Expression.MakeMemberAccess(parameter, property);
  843. var orderByExp = Expression.Lambda(propertyAccess, parameter);
  844. resultExp = Expression.Call(typeof(Queryable), isAsc ? "OrderBy" : "OrderByDescending", new Type[] { typeof(T), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
  845. }
  846. }
  847. if (resultExp != null)
  848. {
  849. tempData = tempData.Provider.CreateQuery<T>(resultExp);
  850. }
  851. total = tempData.Count();
  852. tempData = tempData.Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize).AsQueryable();
  853. return tempData.ToList();
  854. }
  855. catch (Exception)
  856. {
  857. throw;
  858. }
  859. finally
  860. {
  861. if (dbTransaction == null)
  862. {
  863. this.Close();
  864. }
  865. }
  866. }
  867. /// <summary>
  868. /// 查询列表(分页)带表达式条件
  869. /// </summary>
  870. /// <typeparam name="T">类型</typeparam>
  871. /// <param name="condition">表达式</param>
  872. /// <param name="orderField">排序字段</param>
  873. /// <param name="isAsc">排序类型</param>
  874. /// <param name="pageSize">每页数据条数</param>
  875. /// <param name="pageIndex">页码</param>
  876. /// <param name="total">总共数据条数</param>
  877. /// <returns></returns>
  878. public IEnumerable<T> FindList<T>(Expression<Func<T, bool>> condition, string orderField, bool isAsc, int pageSize, int pageIndex, out int total) where T : class, new()
  879. {
  880. try
  881. {
  882. string[] _order = orderField.Split(',');
  883. MethodCallExpression resultExp = null;
  884. var tempData = dbcontext.Set<T>().Where(condition);
  885. foreach (string item in _order)
  886. {
  887. if (!string.IsNullOrEmpty(item))
  888. {
  889. string _orderPart = item;
  890. _orderPart = Regex.Replace(_orderPart, @"\s+", " ");
  891. string[] _orderArry = _orderPart.Split(' ');
  892. string _orderField = _orderArry[0];
  893. bool sort = isAsc;
  894. if (_orderArry.Length == 2)
  895. {
  896. isAsc = _orderArry[1].ToUpper() == "ASC" ? true : false;
  897. }
  898. var parameter = Expression.Parameter(typeof(T), "t");
  899. var property = typeof(T).GetProperty(_orderField);
  900. var propertyAccess = Expression.MakeMemberAccess(parameter, property);
  901. var orderByExp = Expression.Lambda(propertyAccess, parameter);
  902. resultExp = Expression.Call(typeof(Queryable), isAsc ? "OrderBy" : "OrderByDescending", new Type[] { typeof(T), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
  903. }
  904. }
  905. if (resultExp != null)
  906. {
  907. tempData = tempData.Provider.CreateQuery<T>(resultExp);
  908. }
  909. total = tempData.Count();
  910. tempData = tempData.Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize).AsQueryable();
  911. return tempData.ToList();
  912. }
  913. catch (Exception)
  914. {
  915. throw;
  916. }
  917. finally
  918. {
  919. if (dbTransaction == null)
  920. {
  921. this.Close();
  922. }
  923. }
  924. }
  925. /// <summary>
  926. /// 查询列表(分页)根据sql语句
  927. /// </summary>
  928. /// <typeparam name="T"></typeparam>
  929. /// <param name="strSql">sql语句</param>
  930. /// <param name="orderField">排序字段</param>
  931. /// <param name="isAsc">排序类型</param>
  932. /// <param name="pageSize">每页数据条数</param>
  933. /// <param name="pageIndex">页码</param>
  934. /// <param name="total">总共数据条数</param>
  935. /// <returns></returns>
  936. public IEnumerable<T> FindList<T>(string strSql, string orderField, bool isAsc, int pageSize, int pageIndex, out int total) where T : class
  937. {
  938. return FindList<T>(strSql, null, orderField, isAsc, pageSize, pageIndex, out total);
  939. }
  940. /// <summary>
  941. /// 查询列表(分页)根据sql语句
  942. /// </summary>
  943. /// <typeparam name="T"></typeparam>
  944. /// <param name="strSql">sql语句</param>
  945. /// <param name="dbParameter">参数</param>
  946. /// <param name="orderField">排序字段</param>
  947. /// <param name="isAsc">排序类型</param>
  948. /// <param name="pageSize">每页数据条数</param>
  949. /// <param name="pageIndex">页码</param>
  950. /// <param name="total">总共数据条数</param>
  951. /// <returns></returns>
  952. public IEnumerable<T> FindList<T>(string strSql, object dbParameter, string orderField, bool isAsc, int pageSize, int pageIndex, out int total) where T : class
  953. {
  954. try
  955. {
  956. StringBuilder sb = new StringBuilder();
  957. sb.Append(SqlHelper.SqlPageSql(strSql, orderField, isAsc, pageSize, pageIndex));
  958. total = Convert.ToInt32(dbcontext.Database.Connection.ExecuteScalar("Select Count(1) From (" + strSql + ") As t", dbParameter));
  959. return dbcontext.Database.Connection.Query<T>(sb.ToString(), dbParameter, dbTransaction);
  960. }
  961. catch (Exception)
  962. {
  963. throw;
  964. }
  965. finally
  966. {
  967. if (dbTransaction == null)
  968. {
  969. this.Close();
  970. }
  971. }
  972. }
  973. #endregion
  974. #region 数据源查询
  975. /// <summary>
  976. /// 查询数据
  977. /// </summary>
  978. /// <param name="strSql">sql语句</param>
  979. /// <returns></returns>
  980. public DataTable FindTable(string strSql)
  981. {
  982. try
  983. {
  984. var IDataReader = dbcontext.Database.Connection.ExecuteReader(strSql, null, dbTransaction);
  985. return SqlHelper.IDataReaderToDataTable(IDataReader);
  986. }
  987. catch (Exception)
  988. {
  989. throw;
  990. }
  991. finally
  992. {
  993. if (dbTransaction == null)
  994. {
  995. this.Close();
  996. }
  997. }
  998. }
  999. /// <summary>
  1000. /// 查询数据
  1001. /// </summary>
  1002. /// <param name="strSql">sql语句</param>
  1003. /// <param name="dbParameter">参数</param>
  1004. /// <returns></returns>
  1005. public DataTable FindTable(string strSql, object dbParameter)
  1006. {
  1007. try
  1008. {
  1009. var IDataReader = dbcontext.Database.Connection.ExecuteReader(strSql, dbParameter, dbTransaction);
  1010. return SqlHelper.IDataReaderToDataTable(IDataReader);
  1011. }
  1012. catch (Exception exception)
  1013. {
  1014. throw;
  1015. }
  1016. finally
  1017. {
  1018. if (dbTransaction == null)
  1019. {
  1020. this.Close();
  1021. }
  1022. }
  1023. }
  1024. /// <summary>
  1025. /// 查询数据
  1026. /// </summary>
  1027. /// <param name="strSql">sql语句</param>
  1028. /// <param name="orderField">排序字段</param>
  1029. /// <param name="isAsc">排序类型</param>
  1030. /// <param name="pageSize">每页数据条数</param>
  1031. /// <param name="pageIndex">页码</param>
  1032. /// <param name="total">总共数据条数</param>
  1033. /// <returns></returns>
  1034. public DataTable FindTable(string strSql, string orderField, bool isAsc, int pageSize, int pageIndex, out int total)
  1035. {
  1036. return FindTable(strSql, null, orderField, isAsc, pageSize, pageIndex, out total);
  1037. }
  1038. /// <summary>
  1039. /// 查询数据
  1040. /// </summary>
  1041. /// <param name="strSql">sql语句</param>
  1042. /// <param name="dbParameter">参数</param>
  1043. /// <param name="orderField">排序字段</param>
  1044. /// <param name="isAsc">排序类型</param>
  1045. /// <param name="pageSize">每页数据条数</param>
  1046. /// <param name="pageIndex">页码</param>
  1047. /// <param name="total">总共数据条数</param>
  1048. /// <returns></returns>
  1049. public DataTable FindTable(string strSql, object dbParameter, string orderField, bool isAsc, int pageSize, int pageIndex, out int total)
  1050. {
  1051. try
  1052. {
  1053. StringBuilder sb = new StringBuilder();
  1054. sb.Append(SqlHelper.SqlPageSql(strSql, orderField, isAsc, pageSize, pageIndex));
  1055. total = Convert.ToInt32(dbcontext.Database.Connection.ExecuteScalar("Select Count(1) From (" + strSql + ") As t", dbParameter));
  1056. var IDataReader = dbcontext.Database.Connection.ExecuteReader(sb.ToString(), dbParameter, dbTransaction);
  1057. return SqlHelper.IDataReaderToDataTable(IDataReader);
  1058. }
  1059. catch (Exception)
  1060. {
  1061. throw;
  1062. }
  1063. finally
  1064. {
  1065. if (dbTransaction == null)
  1066. {
  1067. this.Close();
  1068. }
  1069. }
  1070. }
  1071. /// <summary>
  1072. /// 获取查询对象
  1073. /// </summary>
  1074. /// <param name="strSql">sql语句</param>
  1075. /// <returns></returns>
  1076. public object FindObject(string strSql)
  1077. {
  1078. return FindObject(strSql, null);
  1079. }
  1080. /// <summary>
  1081. /// 获取查询对象
  1082. /// </summary>
  1083. /// <param name="strSql">sql语句</param>
  1084. /// <param name="dbParameter">参数</param>
  1085. /// <returns></returns>
  1086. public object FindObject(string strSql, object dbParameter)
  1087. {
  1088. try
  1089. {
  1090. return dbcontext.Database.Connection.ExecuteScalar(strSql, dbParameter, dbTransaction);
  1091. }
  1092. catch (Exception)
  1093. {
  1094. throw;
  1095. }
  1096. finally
  1097. {
  1098. if (dbTransaction == null)
  1099. {
  1100. this.Close();
  1101. }
  1102. }
  1103. }
  1104. #endregion
  1105. #region 扩展方法
  1106. /// <summary>
  1107. /// 获取数据库表数据
  1108. /// </summary>
  1109. /// <typeparam name="T">反序列化类型</typeparam>
  1110. /// <returns></returns>
  1111. public IEnumerable<T> GetDBTable<T>() where T : class, new()
  1112. {
  1113. try
  1114. {
  1115. StringBuilder strSql = new StringBuilder();
  1116. strSql.Append(@"DECLARE @TableInfo TABLE ( name VARCHAR(50) , sumrows VARCHAR(11) , reserved VARCHAR(50) , data VARCHAR(50) , index_size VARCHAR(50) , unused VARCHAR(50) , pk VARCHAR(50) )
  1117. DECLARE @TableName TABLE ( name VARCHAR(50) )
  1118. DECLARE @name VARCHAR(50)
  1119. DECLARE @pk VARCHAR(50)
  1120. INSERT INTO @TableName ( name ) SELECT o.name FROM sysobjects o , sysindexes i WHERE o.id = i.id AND o.Xtype = 'U' AND i.indid < 2 ORDER BY i.rows DESC , o.name
  1121. WHILE EXISTS ( SELECT 1 FROM @TableName ) BEGIN SELECT TOP 1 @name = name FROM @TableName DELETE @TableName WHERE name = @name DECLARE @objectid INT SET @objectid = OBJECT_ID(@name) SELECT @pk = COL_NAME(@objectid, colid) FROM sysobjects AS o INNER JOIN sysindexes AS i ON i.name = o.name INNER JOIN sysindexkeys AS k ON k.indid = i.indid WHERE o.xtype = 'PK' AND parent_obj = @objectid AND k.id = @objectid INSERT INTO @TableInfo ( name , sumrows , reserved , data , index_size , unused ) EXEC sys.sp_spaceused @name UPDATE @TableInfo SET pk = @pk WHERE name = @name END
  1122. SELECT F.name as name, F.reserved as reserved, F.data as data, F.index_size as index_size, RTRIM(F.sumrows) AS sumrows , F.unused as unused, ISNULL(p.tdescription, f.name) AS tdescription , F.pk as pk
  1123. FROM @TableInfo F LEFT JOIN ( SELECT name = CASE WHEN A.COLORDER = 1 THEN D.NAME ELSE '' END , tdescription = CASE WHEN A.COLORDER = 1 THEN ISNULL(F.VALUE, '') ELSE '' END FROM SYSCOLUMNS A LEFT JOIN SYSTYPES B ON A.XUSERTYPE = B.XUSERTYPE INNER JOIN SYSOBJECTS D ON A.ID = D.ID AND D.XTYPE = 'U' AND D.NAME <> 'DTPROPERTIES' LEFT JOIN sys.extended_properties F ON D.ID = F.major_id WHERE a.COLORDER = 1 AND F.minor_id = 0 ) P ON F.name = p.name
  1124. ORDER BY f.name ");
  1125. return dbcontext.Database.Connection.Query<T>(strSql.ToString(), null, dbTransaction);
  1126. }
  1127. catch (Exception)
  1128. {
  1129. throw;
  1130. }
  1131. finally
  1132. {
  1133. if (dbTransaction == null)
  1134. {
  1135. this.Close();
  1136. }
  1137. }
  1138. }
  1139. /// <summary>
  1140. /// 获取数据库表字段数据
  1141. /// </summary>
  1142. /// <typeparam name="T">反序列化类型</typeparam>
  1143. /// <param name="tableName">表名</param>
  1144. /// <returns></returns>
  1145. public IEnumerable<T> GetDBTableFields<T>(string tableName) where T : class, new()
  1146. {
  1147. try
  1148. {
  1149. StringBuilder strSql = new StringBuilder();
  1150. strSql.Append(@"SELECT [f_number] = a.colorder , [f_column] = a.name , [f_datatype] = b.name , [f_length] = COLUMNPROPERTY(a.id, a.name, 'PRECISION') , [f_identity] = CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1 THEN '1' ELSE '' END , [f_key] = CASE WHEN EXISTS ( SELECT 1 FROM sysobjects WHERE xtype = 'PK' AND parent_obj = a.id AND name IN ( SELECT name FROM sysindexes WHERE indid IN ( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid = a.colid ) ) ) THEN '1' ELSE '' END , [f_isnullable] = CASE WHEN a.isnullable = 1 THEN '1' ELSE '' END , [f_defaults] = ISNULL(e.text, '') , [f_remark] = ISNULL(g.[value], a.name)
  1151. FROM syscolumns a LEFT JOIN systypes b ON a.xusertype = b.xusertype INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault = e.id LEFT JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id LEFT JOIN sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0
  1152. WHERE d.name = @tableName
  1153. ORDER BY a.id , a.colorder");
  1154. return dbcontext.Database.Connection.Query<T>(strSql.ToString(), new { tableName = tableName }, dbTransaction);
  1155. }
  1156. catch (Exception)
  1157. {
  1158. throw;
  1159. }
  1160. finally
  1161. {
  1162. if (dbTransaction == null)
  1163. {
  1164. this.Close();
  1165. }
  1166. }
  1167. }
  1168. #endregion
  1169. }
  1170. }