Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

1201 wiersze
39 KiB

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