1.关于Dapper.Contrib

  Dapper.Contrib是Dapper的一个拓展类库,Dapper是一个轻量级ORM框架,这个不了解的请自行收集资料,本文主要讲讲,数据库生成实体,并通过实体进行CURD

2.首先,我们了解下Dapper.Contrib需要实体的格式:

  1. using Dapper.Contrib.Extensions;
  2. [Table("StudentSet")]
  3. public partial class StudentSet
  4. {
  5. [Key]
  6. public int Id { get; set; }
  7.  
  8. public string StudentName { get; set; }
  9.  
  10. public string LoginName { get; set; }
  11.  
  12. public string Password { get; set; }
  13.  
  14. public int Age { get; set; }
  15.  
  16. public string Sex { get; set; }
  17.  
  18. public string ClassID { get; set; }
  19.  
  20. public string RuleID { get; set; }
  21.  
  22. public string Status { get; set; }
  23.  
  24. public string UpdateTime { get; set; }
  25.  
  26. public string CreateTime { get; set; }
  27. }

  可以看出,这里,需要注明表名,主键字段,并需要引用Dapper.Contrib.Extensions;的命名空间

3.通过EF来从数据库映射出实体

  在第二点中,我们发现,定义一个实体来符合Dapper.Contrib要求是非常麻烦的,那么,我们来看看如何利用EF框架生成

(3.1)想要生成与数据库对应的实体,就要用到EF的DB First,首先右键你的项目,添加新建项,数据,选择ADO.NET 实体数据模型

添加,来自数据库EF设计器,之后就是连接你的数据库,选择表/视图/存储过程/函数等,之后,我们就能生成一个与数据库对应的实体

这是我随意创建的一个,我们看一下生成的实体,发现,没有数据库注释说明,也不符合Dapper.Contrib的需要

那么,我们来改动Model2.tt这个文件,这里,需要下载一个文件,很小,十几k,GetSummery.ttinclude下载完了后,放到与edmx文件同级目录下:

然后,在配置文件添加数据库连接字串:

  1. <add name="MyDbContext" connectionString="Data Source=yourserver;Initial Catalog=yourdatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />

  改动这个文件:

包含到我们的Model2.tt文件,这是个T4模板文件

<#@ include file="GetSummery.ttinclude" #>

搜索<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
添加

using System.ComponentModel.DataAnnotations;
/// <summary>
/// <#= getTableSummery(code.Escape(entity)) #>
/// </summary>
在之下
搜索<#=codeStringGenerator.Property(edmProperty)#>
添加
/// <summary>
/// <#= getColumnSummery(code.Escape(entity),code.Escape(edmProperty)) #>
/// </summary>

<#=entity.KeyMembers.Contains(edmProperty.Name)?"[Key]":""#>
在上方
保存

这时候查看,嗯,我们的数据库字段说明已经出来了并且符合我们的Dapper.Contrib的需要,这时候可能会报错,前面说过,你需要using Dapper.Contrib.Extensions;

然后,我们就可以愉快的使用Dapper.Contrib了,这里不多说,贴出我自己写的DapperHelper类

  1. using Dapper;
  2. using Dapper.Contrib.Extensions;
  3. using FK.Common;
  4. using FK.Data.Entities;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Data.Common;
  10. using System.Data.SqlClient;
  11. using System.Linq;
  12. using System.Reflection;
  13.  
  14. namespace FK.Web.Data
  15. {
  16. public class DapperHelper
  17. {
  18. public static IDbConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DbConnString"].ConnectionString.DESDecrypt());
  19.  
  20. private static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> KeyProperties = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
  21. private static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> TypeProperties = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
  22.  
  23. #region 增添记录
  24.  
  25. /// <summary>
  26. /// 添加一个实体
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="TableName"></param>
  30. /// <param name="fieldlist"></param>
  31. /// <param name="key"></param>
  32. /// <param name="o"></param>
  33. /// <returns></returns>
  34. public static int AddByEntity<T>(string TableName, string fieldlist, string key, object o)
  35. {
  36. string ColumnsName = string.Empty;
  37. //fildlist=="*"时,通过实体获取列名
  38. if (fieldlist.Trim().Equals("*") || string.IsNullOrEmpty(fieldlist))
  39. {
  40. PropertyInfo[] plist = typeof(T).GetProperties();
  41. string str = "";
  42. foreach (PropertyInfo p in plist)
  43. {
  44. if (!p.PropertyType.IsGenericType && !p.Name.Equals(key))
  45. str += p.Name + ",";
  46.  
  47. }
  48. str = str.Substring(0, str.Length - 1);
  49. fieldlist = str;
  50. }
  51. //根据列名拼接参数名
  52. string[] arrstr = fieldlist.Split(',');
  53. foreach (string s in arrstr)
  54. {
  55. ColumnsName += "@" + s + ",";
  56. }
  57. ColumnsName = ColumnsName.Substring(0, ColumnsName.Length - 1);
  58. fieldlist = "(" + fieldlist + ")";
  59. string sql = "Insert into " + TableName + " " + fieldlist + " values (" + ColumnsName + ")";
  60. //执行插入
  61. var result = connection.Execute(sql, o);
  62. return result;
  63. }
  64.  
  65. /// <summary>
  66. /// 添加一个实体
  67. /// </summary>
  68. /// <typeparam name="T"></typeparam>
  69. /// <param name="criteria"></param>
  70. /// <param name="o"></param>
  71. /// <returns></returns>
  72. public static int AddByEntity<T>(PageCriteria criteria, object o)
  73. {
  74. string ColumnsName = string.Empty;
  75. //fildlist=="*"时,通过实体获取列名
  76. if (criteria.Fields.Trim().Equals("*") || string.IsNullOrEmpty(criteria.Fields))
  77. {
  78. PropertyInfo[] plist = typeof(T).GetProperties();
  79. string str = "";
  80. foreach (PropertyInfo p in plist)
  81. {
  82. if (!p.PropertyType.IsGenericType && !p.Name.Equals(criteria.PrimaryKey))
  83. str += p.Name + ",";
  84.  
  85. }
  86. str = str.Substring(0, str.Length - 1);
  87. criteria.Fields = str;
  88. }
  89. //根据列名拼接参数名
  90. string[] arrstr = criteria.Fields.Split(',');
  91. foreach (string s in arrstr)
  92. {
  93. ColumnsName += "@" + s + ",";
  94. }
  95. ColumnsName = ColumnsName.Substring(0, ColumnsName.Length - 1);
  96. criteria.Fields = "(" + criteria.Fields + ")";
  97. string sql = "Insert into " + criteria.TableName + " " + criteria.Fields + " values (" + ColumnsName + ")";
  98. //执行插入
  99. var result = connection.Execute(sql, o);
  100. return result;
  101. }
  102.  
  103. /// <summary>
  104. /// 事务操作
  105. /// </summary>
  106. /// <typeparam name="T"></typeparam>
  107. /// <param name="sqllist"></param>
  108. /// <param name="objlist"></param>
  109. /// <returns></returns>
  110. public static int TranByEntity<T>(IList<string> sqllist, IList<T> objlist)
  111. {
  112. if (sqllist.Count != objlist.Count) return -100; //参数数量不一致
  113. connection.Open();
  114. IDbTransaction transaction = connection.BeginTransaction();
  115. try
  116. {
  117. for (int i = 0; i < sqllist.Count; i++)
  118. {
  119. connection.Execute(sqllist[i], objlist[i], transaction);
  120. }
  121. transaction.Commit();
  122. return 1;
  123. }
  124. catch
  125. {
  126. transaction.Rollback();
  127. return -1;
  128. }
  129. }
  130.  
  131. #endregion
  132.  
  133. #region 更新记录
  134.  
  135. /// <summary>
  136. /// 更新记录
  137. /// </summary>
  138. /// <param name="TableName">表名</param>
  139. /// <param name="UpdateString">更新的列和值</param>
  140. /// <param name="WhereString">条件</param>
  141. /// <param name="Parameters">参数对象</param>
  142. /// <returns></returns>
  143. public static int Update(string TableName, string UpdateString, string WhereString, object Parameters = null)
  144. {
  145. string sql = "update " + TableName + " set " + UpdateString + " where 1=1 " + WhereString;
  146. var result = connection.Execute(sql, Parameters);
  147. return result;
  148. }
  149.  
  150. /// <summary>
  151. /// 更新记录
  152. /// </summary>
  153. /// <param name="criteria"></param>
  154. /// <param name="UpdateString"></param>
  155. /// <param name="Parameters"></param>
  156. /// <returns></returns>
  157. public static int Update(PageCriteria criteria, object Parameters = null)
  158. {
  159. string sql = "update " + criteria.TableName + " set " + criteria.Fields + " where 1=1 " + criteria.Condition;
  160. var result = connection.Execute(sql, Parameters);
  161. return result;
  162. }
  163.  
  164. /// <summary>
  165. /// 更新实体
  166. /// </summary>
  167. /// <typeparam name="T">实体类型</typeparam>
  168. /// <param name="newt">实体对象,主键不能缺少</param>
  169. /// <returns></returns>
  170. public static int UpdateEntity<T>(T newt)
  171. {
  172. string TableName = typeof(T).Name;
  173. PropertyInfo[] plist = typeof(T).GetProperties();
  174. var type = typeof(T);
  175. var keyProperties = KeyPropertiesCache(type).ToList();
  176. string condition = "";
  177. foreach (var item in keyProperties)
  178. {
  179. if (!item.PropertyType.IsGenericType)
  180. condition = item.Name + "=@" + item.Name + " and";
  181. }
  182. string field = "";
  183. foreach (PropertyInfo p in plist)
  184. {
  185. if (!p.PropertyType.IsGenericType)
  186. field += p.Name + ",";
  187. }
  188. field = field.Substring(0, field.Length - 1);
  189. condition = condition.Substring(0, condition.Length - 4);
  190. T oldt = GetModel<T>(TableName, field, "where 1=1 " + condition, newt);
  191. if (newt == null || oldt == null) return 0;
  192. if (newt.Equals(oldt)) return 0;
  193. string objVal1 = string.Empty;
  194. string objVal2 = string.Empty;
  195. string updatestr = "";
  196. foreach (PropertyInfo p in plist)
  197. {
  198. objVal1 = p.GetValue(newt, null) == null ? string.Empty : p.GetValue(newt, null).ToString();
  199. objVal2 = p.GetValue(oldt, null) == null ? string.Empty : p.GetValue(oldt, null).ToString();
  200. if (objVal1 != objVal2)
  201. updatestr += p.Name + "=@" + p.Name + ",";
  202. }
  203. updatestr = updatestr.Substring(0, updatestr.Length - 1);
  204. string sql = "update " + TableName + " set " + updatestr + " where 1=1 " + condition;
  205. var result = connection.Execute(sql, newt);
  206. return result;
  207. }
  208.  
  209. /// <summary>
  210. /// 更新实体,需要旧的实体对象
  211. /// </summary>
  212. /// <typeparam name="T">实体类型</typeparam>
  213. /// <param name="oldt">旧的实体对象</param>
  214. /// <param name="newt">新的实体对象</param>
  215. /// <returns></returns>
  216. public static int UpdateEntity<T>(T oldt, T newt)
  217. {
  218. string TableName = typeof(T).Name;
  219. PropertyInfo[] plist = typeof(T).GetProperties();
  220. var type = typeof(T);
  221. var keyProperties = KeyPropertiesCache(type).ToList();
  222. if (newt == null || oldt == null) return 0;
  223. if (newt.Equals(oldt)) return 0;
  224. string objVal1 = string.Empty;
  225. string objVal2 = string.Empty;
  226. string updatestr = "";
  227. foreach (PropertyInfo p in plist)
  228. {
  229. objVal1 = p.GetValue(newt, null) == null ? string.Empty : p.GetValue(newt, null).ToString();
  230. objVal2 = p.GetValue(oldt, null) == null ? string.Empty : p.GetValue(oldt, null).ToString();
  231. if (objVal1 != objVal2&& !p.PropertyType.IsGenericType)
  232. updatestr += p.Name + "=@" + p.Name + ",";
  233. }
  234. updatestr = updatestr.Substring(0, updatestr.Length - 1);
  235. string condition = "";
  236. foreach (var item in keyProperties)
  237. {
  238. if (!item.PropertyType.IsGenericType)
  239. condition = item.Name + "=@" + item.Name + " and";
  240. }
  241. condition = condition.Substring(0, condition.Length - 4);
  242. string sql = "update " + TableName + " set " + updatestr + " where 1=1 " + condition;
  243. var result = connection.Execute(sql, newt);
  244. return result;
  245. }
  246.  
  247. #endregion
  248.  
  249. #region 删除记录
  250.  
  251. /// <summary>
  252. /// 删除记录
  253. /// </summary>
  254. /// <param name="TableName">表名</param>
  255. /// <param name="WhereString">条件</param>
  256. /// <param name="Parameters">参数对象</param>
  257. /// <returns></returns>
  258. public static int Delete(string TableName, string WhereString, object Parameters = null)
  259. {
  260. string sql = "delete from " + TableName + " where 1=1 " + WhereString;
  261. var result = connection.Execute(sql, Parameters);
  262. return result;
  263. }
  264.  
  265. /// <summary>
  266. /// 删除
  267. /// </summary>
  268. /// <param name="criteria"></param>
  269. /// <param name="Parameters"></param>
  270. /// <returns></returns>
  271. public static int Delete(PageCriteria criteria, object Parameters = null)
  272. {
  273. string sql = "delete from " + criteria.TableName + " where 1=1 " + criteria.Condition;
  274. var result = connection.Execute(sql, Parameters);
  275. return result;
  276. }
  277.  
  278. #endregion
  279.  
  280. #region 查询操作
  281.  
  282. /// <summary>
  283. /// 查询返回DataSet
  284. /// </summary>
  285. /// <param name="TableName"></param>
  286. /// <param name="FieldString"></param>
  287. /// <param name="WhereString"></param>
  288. /// <param name="Parameters"></param>
  289. /// <returns></returns>
  290. public static DataSet QueryGetDS(string TableName, string FieldString, string WhereString, object Parameters = null)
  291. {
  292. DataSet ds = new XDataSet();
  293. string sql = "select " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
  294. var result = connection.ExecuteReader(sql, Parameters);
  295. try
  296. {
  297. ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
  298. }
  299. finally { result.Close(); }
  300. return ds;
  301. }
  302.  
  303. /// <summary>
  304. /// 查询返回DataSet
  305. /// </summary>
  306. /// <param name="criteria"></param>
  307. /// <param name="Parameters"></param>
  308. /// <returns></returns>
  309. public static DataSet QueryGetDS(PageCriteria criteria, object Parameters = null)
  310. {
  311. DataSet ds = new XDataSet();
  312. string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
  313. var result = connection.ExecuteReader(sql, Parameters);
  314. try
  315. {
  316. ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
  317. }
  318. finally { result.Close(); }
  319. return ds;
  320. }
  321.  
  322. /// <summary>
  323. /// 查询返回DataTable
  324. /// </summary>
  325. /// <param name="TableName"></param>
  326. /// <param name="FieldString"></param>
  327. /// <param name="WhereString"></param>
  328. /// <param name="Parameters"></param>
  329. /// <returns></returns>
  330. public static DataTable QueryGetDT(string TableName, string FieldString, string WhereString, object Parameters = null)
  331. {
  332. DataTable dt = new DataTable();
  333. string sql = "select " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
  334. var result = connection.ExecuteReader(sql, Parameters);
  335. try
  336. {
  337. dt.Load(result);
  338. }
  339. finally { result.Close(); }
  340. return dt;
  341. }
  342.  
  343. /// <summary>
  344. /// 查询返回DataTable
  345. /// </summary>
  346. /// <param name="criteria"></param>
  347. /// <param name="Parameters"></param>
  348. /// <returns></returns>
  349. public static DataTable QueryGetDT(PageCriteria criteria, object Parameters = null)
  350. {
  351. DataTable dt = new DataTable();
  352. string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
  353. var result = connection.ExecuteReader(sql, Parameters);
  354. try
  355. {
  356. dt.Load(result);
  357. }
  358. finally { result.Close(); }
  359. return dt;
  360. }
  361.  
  362. /// <summary>
  363. /// 查询查询返回list
  364. /// </summary>
  365. /// <param name="TableName"></param>
  366. /// <param name="FieldString"></param>
  367. /// <param name="WhereString"></param>
  368. /// <param name="Parameters"></param>
  369. /// <returns>对象集</returns>
  370. public static List<T> Query<T>(string TableName, string FieldString, string WhereString, object Parameters = null)
  371. {
  372. string sql = "select " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
  373. var result = connection.Query<T>(sql, Parameters).ToList();
  374. return result;
  375. }
  376.  
  377. /// <summary>
  378. /// 查询返回list
  379. /// </summary>
  380. /// <param name="criteria"></param>
  381. /// <param name="Parameters"></param>
  382. /// <returns></returns>
  383. public static List<T> Query<T>(PageCriteria criteria, object Parameters = null)
  384. {
  385. string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
  386. var result = connection.Query<T>(sql, Parameters).ToList();
  387. return result;
  388. }
  389.  
  390. /// <summary>
  391. /// 获取模型
  392. /// </summary>
  393. /// <typeparam name="T"></typeparam>
  394. /// <param name="TableName"></param>
  395. /// <param name="FieldString"></param>
  396. /// <param name="WhereString"></param>
  397. /// <param name="Parameters"></param>
  398. /// <returns></returns>
  399. public static T GetModel<T>(string TableName, string FieldString, string WhereString, object Parameters = null)
  400. {
  401. string sql = "select top 1 " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
  402. var result = connection.Query<T>(sql, Parameters).FirstOrDefault();
  403. return result;
  404. }
  405.  
  406. /// <summary>
  407. /// 获取模型
  408. /// </summary>
  409. /// <typeparam name="T"></typeparam>
  410. /// <param name="criteria"></param>
  411. /// <param name="Parameters"></param>
  412. /// <returns></returns>
  413. public static T GetModel<T>(PageCriteria criteria, object Parameters = null)
  414. {
  415. string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
  416. var result = connection.Query<T>(sql, Parameters).FirstOrDefault();
  417. return result;
  418. }
  419.  
  420. /// <summary>
  421. /// 获取实体通过实体
  422. /// </summary>
  423. /// <typeparam name="T">实体类型</typeparam>
  424. /// <param name="t">实体对象</param>
  425. /// <param name="condition">and field1=@field1 and field2=@field2</param>
  426. /// <returns></returns>
  427. public static T GetModel<T>(T t, string condition=null)
  428. {
  429. string TableName = typeof(T).Name;
  430. PropertyInfo[] plist = typeof(T).GetProperties();
  431. var type = typeof(T);
  432. var keyProperties = KeyPropertiesCache(type).ToList();
  433. if (string.IsNullOrEmpty(condition)){
  434. foreach (var item in keyProperties)
  435. {
  436. if (!item.PropertyType.IsGenericType)
  437. condition =" and " + item.Name + "=@" + item.Name ;
  438. }
  439. }
  440. string field = "";
  441. foreach (PropertyInfo p in plist)
  442. {
  443. if (!p.PropertyType.IsGenericType)
  444. field += p.Name + ",";
  445. }
  446. field = field.Substring(0, field.Length - 1);
  447. string sql = "select top 1 " + field + " from " + TableName + " where 1=1 " + condition;
  448. var result = connection.Query<T>(sql, t).FirstOrDefault();
  449. return result;
  450. }
  451.  
  452. /// <summary>
  453. /// 通用分页获取数据
  454. /// </summary>
  455. /// <typeparam name="T"></typeparam>
  456. /// <param name="criteria"></param>
  457. /// <param name="param"></param>
  458. /// <returns></returns>
  459. public static PageDataView<T> GetPageModelList<T>(PageCriteria criteria)
  460. {
  461. var p = new DynamicParameters();
  462. string proName = "Fgly_Public_Pagination";
  463. p.Add("TableName", criteria.TableName);
  464. p.Add("PrimaryKey", criteria.PrimaryKey);
  465. p.Add("Fields", criteria.Fields);
  466. p.Add("Filter", criteria.Condition);
  467. p.Add("CurrentPage", criteria.CurrentPage);
  468. p.Add("PageSize", criteria.PageSize);
  469. p.Add("Order", criteria.Sort);
  470. p.Add("TotalCount", dbType: DbType.Int32, direction: ParameterDirection.Output);
  471.  
  472. connection.Open();
  473. var pageData = new PageDataView<T>
  474. {
  475. Items = connection.Query<T>(proName, p, commandType: CommandType.StoredProcedure).ToList()
  476. };
  477. connection.Close();
  478. pageData.TotalNum = p.Get<int>("TotalCount");
  479. pageData.TotalPageCount = Convert.ToInt32(Math.Ceiling(pageData.TotalNum * 1.0 / criteria.PageSize));
  480. pageData.CurrentPage = criteria.CurrentPage > pageData.TotalPageCount ? pageData.TotalPageCount : criteria.CurrentPage;
  481. return pageData;
  482. }
  483.  
  484. /// <summary>
  485. /// 分页获取数据
  486. /// </summary>
  487. /// <param name="criteria"></param>
  488. /// <param name="TotalCount"></param>
  489. /// <returns></returns>
  490. public static DataTable GetPageProc(PageCriteria criteria,ref int TotalCount)
  491. {
  492. var p = new DynamicParameters();
  493. string proName = "Fgly_Public_Pagination";
  494. p.Add("TableName", criteria.TableName);
  495. p.Add("PrimaryKey", criteria.PrimaryKey);
  496. p.Add("Fields", criteria.Fields);
  497. p.Add("Filter", criteria.Condition);
  498. p.Add("CurrentPage", criteria.CurrentPage);
  499. p.Add("PageSize", criteria.PageSize);
  500. p.Add("Order", criteria.Sort);
  501. p.Add("TotalCount", dbType: DbType.Int32, direction: ParameterDirection.Output);
  502. DataTable dt = new DataTable();
  503. //connection.Open();
  504. var result = connection.ExecuteReader(proName, p, commandType: CommandType.StoredProcedure);
  505. try
  506. {
  507. dt.Load(result);
  508. }
  509. finally { result.Close(); }
  510. connection.Close();
  511. TotalCount = p.Get<int>("TotalCount");
  512. return dt;
  513. }
  514.  
  515. /// <summary>
  516. /// 分页获取数据
  517. /// </summary>
  518. /// <param name="criteria"></param>
  519. /// <param name="TotalCount"></param>
  520. /// <returns></returns>
  521. public static IList<T> GetPageProc<T>(PageCriteria criteria, ref int TotalCount)
  522. {
  523. var p = new DynamicParameters();
  524. string proName = "Fgly_Public_Pagination";
  525. p.Add("TableName", criteria.TableName);
  526. p.Add("PrimaryKey", criteria.PrimaryKey);
  527. p.Add("Fields", criteria.Fields);
  528. p.Add("Filter", criteria.Condition);
  529. p.Add("CurrentPage", criteria.CurrentPage);
  530. p.Add("PageSize", criteria.PageSize);
  531. p.Add("Order", criteria.Sort);
  532. p.Add("TotalCount", dbType: DbType.Int32, direction: ParameterDirection.Output);
  533. connection.Open();
  534. var result = connection.Query<T>(proName, p, commandType: CommandType.StoredProcedure).ToList();
  535. connection.Close();
  536. TotalCount = p.Get<int>("TotalCount");
  537. return result;
  538. }
  539. #endregion
  540.  
  541. #region 执行存储过程
  542. /// <summary>
  543. /// 执行存储过程并返回List
  544. /// </summary>
  545. /// <param name="proName"></param>
  546. /// <param name="p"></param>
  547. /// <returns></returns>
  548. public static List<T> ExtProcGetList<T>(string proName, object p = null)
  549. {
  550. var result = connection.Query<T>(proName, p, commandType: CommandType.StoredProcedure).ToList();
  551. return result;
  552. }
  553.  
  554. /// <summary>
  555. /// 执行存储过程并返回DataSet
  556. /// </summary>
  557. /// <param name="proName"></param>
  558. /// <param name="p"></param>
  559. /// <returns></returns>
  560. public static DataSet ExtProcGetDS(string proName, object p=null)
  561. {
  562. DataSet ds = new XDataSet();
  563. var result = connection.ExecuteReader(proName, p, commandType: CommandType.StoredProcedure);
  564. try
  565. {
  566. ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
  567. }
  568. finally { result.Close(); }
  569. return ds;
  570. }
  571.  
  572. /// <summary>
  573. /// 执行存储过程并返回DataTable
  574. /// </summary>
  575. /// <param name="proName"></param>
  576. /// <param name="p"></param>
  577. /// <returns></returns>
  578. public static DataTable ExtProcGetDT(string proName, object p = null)
  579. {
  580. DataTable dt = new DataTable();
  581. var result = connection.ExecuteReader(proName, p, commandType: CommandType.StoredProcedure);
  582. try
  583. {
  584. dt.Load(result);
  585. }
  586. finally { result.Close(); }
  587. return dt;
  588. }
  589.  
  590. /// <summary>
  591. /// 执行存储过程返回受影响的行数
  592. /// </summary>
  593. /// <param name="proName"></param>
  594. /// <param name="p"></param>
  595. /// <returns></returns>
  596. public static int IntExtProc(string proName,object p = null)
  597. {
  598. int result = connection.Execute(proName, p, commandType: CommandType.StoredProcedure);
  599. return result;
  600. }
  601.  
  602. /// <summary>
  603. /// 执行存储过程返回一个值
  604. /// </summary>
  605. /// <param name="proName"></param>
  606. /// <param name="p"></param>
  607. /// <returns></returns>
  608. public static object ExtProcScale(string proName, object p = null)
  609. {
  610. object result = connection.ExecuteScalar(proName, p, commandType: CommandType.StoredProcedure);
  611. return result;
  612. }
  613.  
  614. #endregion
  615.  
  616. #region 执行Sql语句
  617.  
  618. /// <summary>
  619. /// 执行sql返回list
  620. /// </summary>
  621. /// <typeparam name="T"></typeparam>
  622. /// <param name="sql"></param>
  623. /// <param name="p"></param>
  624. /// <returns></returns>
  625. public static List<T> ExtSqlGetList<T>(string sql,object p = null)
  626. {
  627. var result = connection.Query<T>(sql, p).ToList();
  628. return result;
  629. }
  630.  
  631. /// <summary>
  632. /// 执行Sql语句返回模型
  633. /// </summary>
  634. /// <typeparam name="T"></typeparam>
  635. /// <param name="sql"></param>
  636. /// <param name="parameter"></param>
  637. /// <returns></returns>
  638. public static T ExtSqlGetModel<T>(string sql, object parameter)
  639. {
  640. var result = connection.Query<T>(sql, parameter).ToList().FirstOrDefault();
  641. return result;
  642. }
  643.  
  644. /// <summary>
  645. /// 执行sql返回DataSet
  646. /// </summary>
  647. /// <param name="sql"></param>
  648. /// <param name="p"></param>
  649. /// <returns></returns>
  650. public static DataSet ExtSqlGetDS(string sql,object p = null)
  651. {
  652. DataSet ds = new XDataSet();
  653. var result = connection.ExecuteReader(sql, p);
  654. try
  655. {
  656. ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
  657. }
  658. finally { result.Close(); }
  659. return ds;
  660. }
  661.  
  662. /// <summary>
  663. /// 执行SQL返回DataTable
  664. /// </summary>
  665. /// <param name="sql"></param>
  666. /// <param name="p"></param>
  667. /// <returns></returns>
  668. public static DataTable ExtSqlGetDT(string sql, object p = null)
  669. {
  670. DataTable dt = new DataTable();
  671. var result = connection.ExecuteReader(sql, p);
  672. try
  673. {
  674. dt.Load(result);
  675. }
  676. finally { result.Close(); }
  677. return dt;
  678. }
  679.  
  680. /// <summary>
  681. /// 执行SQL返回受影响的行数
  682. /// </summary>
  683. /// <param name="sql"></param>
  684. /// <param name="p"></param>
  685. /// <returns></returns>
  686. public static int IntExtSql(string sql, object p = null)
  687. {
  688. int result = connection.Execute(sql, p);
  689. return result;
  690. }
  691.  
  692. /// <summary>
  693. /// 执行SQL返回一个值
  694. /// </summary>
  695. /// <param name="sql"></param>
  696. /// <param name="p"></param>
  697. /// <returns></returns>
  698. public static object ExtSqlScale(string sql,object p = null)
  699. {
  700. object result = connection.ExecuteScalar(sql, p);
  701. return result;
  702. }
  703. #endregion
  704.  
  705. #region 扩展需要方法
  706. private static List<PropertyInfo> KeyPropertiesCache(Type type)
  707. {
  708. var allProperties = TypePropertiesCache(type);
  709. var keyProperties = allProperties.Where(p => p.GetCustomAttributes(true).Any(a => a is Dapper.Contrib.Extensions.KeyAttribute)).ToList();
  710.  
  711. if (keyProperties.Count == 0)
  712. {
  713. var idProp = allProperties.Find(p => string.Equals(p.Name, "id", StringComparison.CurrentCultureIgnoreCase));
  714. if (idProp != null && !idProp.GetCustomAttributes(true).Any(a => a is ExplicitKeyAttribute))
  715. {
  716. keyProperties.Add(idProp);
  717. }
  718. }
  719.  
  720. KeyProperties[type.TypeHandle] = keyProperties;
  721. return keyProperties;
  722. }
  723.  
  724. private static List<PropertyInfo> TypePropertiesCache(Type type)
  725. {
  726. var properties = type.GetProperties().Where(IsWriteable).ToArray();
  727. TypeProperties[type.TypeHandle] = properties;
  728. return properties.ToList();
  729. }
  730.  
  731. private static bool IsWriteable(PropertyInfo pi)
  732. {
  733. var attributes = pi.GetCustomAttributes(typeof(WriteAttribute), false).AsList();
  734. if (attributes.Count != 1) return true;
  735.  
  736. var writeAttribute = (WriteAttribute)attributes[0];
  737. return writeAttribute.Write;
  738. }
  739.  
  740. #endregion
  741.  
  742. }
  743.  
  744. public class XLoadAdapter : DataAdapter
  745. {
  746. public XLoadAdapter()
  747. {
  748. }
  749.  
  750. public int FillFromReader(DataSet ds, IDataReader dataReader, int startRecord, int maxRecords)
  751. {
  752. return this.Fill(ds, "Table", dataReader, startRecord, maxRecords);
  753. }
  754. }
  755.  
  756. public class XDataSet : DataSet
  757. {
  758. public override void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler handler, params DataTable[] tables)
  759. {
  760. XLoadAdapter adapter = new XLoadAdapter
  761. {
  762. FillLoadOption = loadOption,
  763. MissingSchemaAction = MissingSchemaAction.AddWithKey
  764. };
  765. if (handler != null)
  766. {
  767. adapter.FillError += handler;
  768. }
  769. adapter.FillFromReader(this, reader, 0, 0);
  770. if (!reader.IsClosed && !reader.NextResult())
  771. {
  772. reader.Close();
  773. }
  774. }
  775. }
  776. }

  这个类,包含了对实体操作,执行sql语句,执行存储过程,返回list<T>,DataSet,DataTable,int,object等操作,可能需要你手动添加一些引用,这边在贴出我的条件类,分页类,在这个类中有用到:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FK.Data.Entities
{
public class PageCriteria
{
private string _TableName;
/// <summary>
/// 表名
/// </summary>
public string TableName
{
get { return _TableName; }
set { _TableName = value; }
}
private string _Fileds = "*";
/// <summary>
/// 字段(逗号隔开,默认*)
/// </summary>
public string Fields
{
get { return _Fileds; }
set { _Fileds = value; }
}
private string _PrimaryKey = "ID";
/// <summary>
/// 主键名
/// </summary>
public string PrimaryKey
{
get { return _PrimaryKey; }
set { _PrimaryKey = value; }
}
private int _PageSize = 10;
/// <summary>
/// 每页记录数,默认10
/// </summary>
public int PageSize
{
get { return _PageSize; }
set { _PageSize = value; }
}
private int _CurrentPage = 1;
/// <summary>
/// 当前页
/// </summary>
public int CurrentPage
{
get { return _CurrentPage; }
set { _CurrentPage = value; }
}
private string _Sort = string.Empty;
/// <summary>
/// 排序
/// </summary>
public string Sort
{
get { return _Sort; }
set { _Sort = value; }
}
private string _Condition = string.Empty;
/// <summary>
/// 条件
/// </summary>
public string Condition
{
get { return _Condition; }
set { _Condition = value; }
}
private int _RecordCount;
/// <summary>
/// 记录数
/// </summary>
public int RecordCount
{
get { return _RecordCount; }
set { _RecordCount = value; }
}
}
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FK.Data.Entities
{
public class PageDataView<T>
{
private int _TotalNum;
public PageDataView()
{
this._Items = new List<T>();
}
/// <summary>
/// 记录数
/// </summary>
public int TotalNum
{
get { return _TotalNum; }
set { _TotalNum = value; }
}
private IList<T> _Items;
/// <summary>
/// 列表
/// </summary>
public IList<T> Items
{
get { return _Items; }
set { _Items = value; }
}
/// <summary>
/// 当前页
/// </summary>
public int CurrentPage { get; set; }
/// <summary>
/// 总页数,输出参数
/// </summary>
public int TotalPageCount { get; set; }
}
}

  好了,还有什么疑问,或者建议,请在评论中与我讨论,感谢你的阅读,再见

Dapper.Contrib拓展及数据库生成实体的更多相关文章

  1. VS2015 +EF6 连接MYSQL数据库生成实体

      VS2015 +EF6 连接MYSQL数据库生成实体   已安装软件:VS2015                       XAMPP Control Panel(Mysql服务器)      ...

  2. NetCore +EF+Mysql 从数据库生成实体类到项目

    1.点击“工具”->“NuGet包管理器”->“程序包管理器控制台” 分别安装以下几个包 Mysql 版本: Install-Package MySql.Data.EntityFramew ...

  3. NetCore +EFCore+SqlServer根据数据库生成实体类到项目中

    转载自:https://www.cnblogs.com/yangjinwang/p/9516988.html 1.点击“工具”->“NuGet包管理器”->“程序包管理器控制台” 分别安装 ...

  4. .net core 根据数据库生成实体类

    微软最近几年在跨平台上不断发力,很多.net程序员也摩拳擦掌,对微软寄以厚望.就在最近,微软还推出了asp .net core2.0预览版. 通过对.net core的简单尝试,我发现以往我们开发MV ...

  5. Java的generator工具类,数据库生成实体类和映射文件

    首先需要几个jar包: freemarker-2.3.23.jar log4j-1.2.16.jar mybatis-3.2.3.jar mybatis-generator-core-1.3.2.ja ...

  6. VS根据数据库生成实体类

    一.在类库项目上添加新项 二. 三.依次填入数据库连接 选择数据库 就可以生成数据库实体

  7. .Net Core 从MySql数据库生成实体类 Entity Model

    1.首先建测试库 2.新建一个.Net Core 项目 3. cd到项目里面执行命令: dotnet add package MySql.Data.EntityFrameworkCore 4.继续执行 ...

  8. idea如何通过数据库生成实体类

    ---恢复内容开始--- https://blog.csdn.net/liu_yulong/article/details/72910588 ---恢复内容结束---

  9. 在eclipse中生成实体类

    1.在eclipse的windows中选中preferences在查询框中输入driver definition 2.点击add在Name/type中选中mysql jdbc driver 5.1然后 ...

随机推荐

  1. 第四章 JavaScript操作DOM对象

    第四章   JavaScript操作DOM对象 一.DOM操作 DOM是Document Object Model的缩写,即文档对象模型,是基于文档编程的一套API接口,1988年,W3C发布了第一级 ...

  2. linux——网络基础

    装完linux系统要对网络(ip地址,子网掩码,网关,DNS)进行配置,才能连接网络 一,开启网卡eth0 CentOS显示没有网卡(eth0) 2.设置静态IP vim /etc/sysconfig ...

  3. RSA的公钥、私钥

    一.举个例子 1.发消息 用对方的公钥给对方发消息 2.发公告 发公告的时候,用自己的私钥形成签名! 二.加密和签名 RSA的公钥.私钥是互相对应的,RSA会生成两个密钥,你可以把任何一个用于公钥,然 ...

  4. spring-oauth-server实践:使用授权方式四:client_credentials 模式的客户端和服务端交互

    spring-oauth-server入门(1-11)使用授权方式四:client_credentials 模式的客戶端 一.客户端逻辑 1.界面入口(credentials_access_token ...

  5. Spark入门(1-1)什么是spark,spark和hadoop

    一.Spark是什么? Apache Spark 是专为大规模数据处理而设计的快速通用的计算引擎,可用来构建大型的.低延迟的数据分析应用程序. Spark是UC Berkeley AMP lab (加 ...

  6. linux下mongodb安装、服务器、客户端、备份、账户命令

    在linux环境安装mongoDB: 一般认为偶数版本为稳定版 如 1.6.x,奇数版本为开发版如1.7.x 32bit的mongoDB最大能存放2g的数据,64bit没有限制 方法1: 终端执行: ...

  7. monogodb3.4安装修改,权限设置

    下载地址:https://www.mongodb.com/download-center#community 这里的方法只对应3.4,别的有没有效果请自行判断. 下载后按默认下一步. 默认安装地址  ...

  8. SQL Server 2008 R2 安装注意事项

    上个星期自己第一次安装SQL Server 2008 R2,安装失败几次,结果用了将近1天的时间安装,最后成功了. 心得:1.安装SQL Server 2008 R2时,最好在第一次就安装成功.在百度 ...

  9. Java面试题2--数据类型

    1. Java的数据类型? 2. Java的封装类型? 3. 基本类型和封装类型的区别? 基本类型只能按值传递,而对应的封装类是按引用传递的. 基本类型是在堆栈上创建的,而所有的对象类型都是在堆上创建 ...

  10. iframe 里的高度自适应

    由于公司里的很多东西都要用到iframe 导致我不得不各种百度 首先是自适应高度 // document.domain = "caibaojian.com"; function s ...