Dapper.Contrib拓展及数据库生成实体
1.关于Dapper.Contrib
Dapper.Contrib是Dapper的一个拓展类库,Dapper是一个轻量级ORM框架,这个不了解的请自行收集资料,本文主要讲讲,数据库生成实体,并通过实体进行CURD
2.首先,我们了解下Dapper.Contrib需要实体的格式:
- using Dapper.Contrib.Extensions;
- [Table("StudentSet")]
- public partial class StudentSet
- {
- [Key]
- public int Id { get; set; }
- public string StudentName { get; set; }
- public string LoginName { get; set; }
- public string Password { get; set; }
- public int Age { get; set; }
- public string Sex { get; set; }
- public string ClassID { get; set; }
- public string RuleID { get; set; }
- public string Status { get; set; }
- public string UpdateTime { get; set; }
- public string CreateTime { get; set; }
- }
可以看出,这里,需要注明表名,主键字段,并需要引用Dapper.Contrib.Extensions;的命名空间
3.通过EF来从数据库映射出实体
在第二点中,我们发现,定义一个实体来符合Dapper.Contrib要求是非常麻烦的,那么,我们来看看如何利用EF框架生成
(3.1)想要生成与数据库对应的实体,就要用到EF的DB First,首先右键你的项目,添加新建项,数据,选择ADO.NET 实体数据模型
添加,来自数据库EF设计器,之后就是连接你的数据库,选择表/视图/存储过程/函数等,之后,我们就能生成一个与数据库对应的实体
这是我随意创建的一个,我们看一下生成的实体,发现,没有数据库注释说明,也不符合Dapper.Contrib的需要
那么,我们来改动Model2.tt这个文件,这里,需要下载一个文件,很小,十几k,GetSummery.ttinclude下载完了后,放到与edmx文件同级目录下:
然后,在配置文件添加数据库连接字串:
- <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类
- using Dapper;
- using Dapper.Contrib.Extensions;
- using FK.Common;
- using FK.Data.Entities;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Common;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Reflection;
- namespace FK.Web.Data
- {
- public class DapperHelper
- {
- public static IDbConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DbConnString"].ConnectionString.DESDecrypt());
- private static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> KeyProperties = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
- private static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> TypeProperties = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
- #region 增添记录
- /// <summary>
- /// 添加一个实体
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="TableName"></param>
- /// <param name="fieldlist"></param>
- /// <param name="key"></param>
- /// <param name="o"></param>
- /// <returns></returns>
- public static int AddByEntity<T>(string TableName, string fieldlist, string key, object o)
- {
- string ColumnsName = string.Empty;
- //fildlist=="*"时,通过实体获取列名
- if (fieldlist.Trim().Equals("*") || string.IsNullOrEmpty(fieldlist))
- {
- PropertyInfo[] plist = typeof(T).GetProperties();
- string str = "";
- foreach (PropertyInfo p in plist)
- {
- if (!p.PropertyType.IsGenericType && !p.Name.Equals(key))
- str += p.Name + ",";
- }
- str = str.Substring(0, str.Length - 1);
- fieldlist = str;
- }
- //根据列名拼接参数名
- string[] arrstr = fieldlist.Split(',');
- foreach (string s in arrstr)
- {
- ColumnsName += "@" + s + ",";
- }
- ColumnsName = ColumnsName.Substring(0, ColumnsName.Length - 1);
- fieldlist = "(" + fieldlist + ")";
- string sql = "Insert into " + TableName + " " + fieldlist + " values (" + ColumnsName + ")";
- //执行插入
- var result = connection.Execute(sql, o);
- return result;
- }
- /// <summary>
- /// 添加一个实体
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="criteria"></param>
- /// <param name="o"></param>
- /// <returns></returns>
- public static int AddByEntity<T>(PageCriteria criteria, object o)
- {
- string ColumnsName = string.Empty;
- //fildlist=="*"时,通过实体获取列名
- if (criteria.Fields.Trim().Equals("*") || string.IsNullOrEmpty(criteria.Fields))
- {
- PropertyInfo[] plist = typeof(T).GetProperties();
- string str = "";
- foreach (PropertyInfo p in plist)
- {
- if (!p.PropertyType.IsGenericType && !p.Name.Equals(criteria.PrimaryKey))
- str += p.Name + ",";
- }
- str = str.Substring(0, str.Length - 1);
- criteria.Fields = str;
- }
- //根据列名拼接参数名
- string[] arrstr = criteria.Fields.Split(',');
- foreach (string s in arrstr)
- {
- ColumnsName += "@" + s + ",";
- }
- ColumnsName = ColumnsName.Substring(0, ColumnsName.Length - 1);
- criteria.Fields = "(" + criteria.Fields + ")";
- string sql = "Insert into " + criteria.TableName + " " + criteria.Fields + " values (" + ColumnsName + ")";
- //执行插入
- var result = connection.Execute(sql, o);
- return result;
- }
- /// <summary>
- /// 事务操作
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="sqllist"></param>
- /// <param name="objlist"></param>
- /// <returns></returns>
- public static int TranByEntity<T>(IList<string> sqllist, IList<T> objlist)
- {
- if (sqllist.Count != objlist.Count) return -100; //参数数量不一致
- connection.Open();
- IDbTransaction transaction = connection.BeginTransaction();
- try
- {
- for (int i = 0; i < sqllist.Count; i++)
- {
- connection.Execute(sqllist[i], objlist[i], transaction);
- }
- transaction.Commit();
- return 1;
- }
- catch
- {
- transaction.Rollback();
- return -1;
- }
- }
- #endregion
- #region 更新记录
- /// <summary>
- /// 更新记录
- /// </summary>
- /// <param name="TableName">表名</param>
- /// <param name="UpdateString">更新的列和值</param>
- /// <param name="WhereString">条件</param>
- /// <param name="Parameters">参数对象</param>
- /// <returns></returns>
- public static int Update(string TableName, string UpdateString, string WhereString, object Parameters = null)
- {
- string sql = "update " + TableName + " set " + UpdateString + " where 1=1 " + WhereString;
- var result = connection.Execute(sql, Parameters);
- return result;
- }
- /// <summary>
- /// 更新记录
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="UpdateString"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static int Update(PageCriteria criteria, object Parameters = null)
- {
- string sql = "update " + criteria.TableName + " set " + criteria.Fields + " where 1=1 " + criteria.Condition;
- var result = connection.Execute(sql, Parameters);
- return result;
- }
- /// <summary>
- /// 更新实体
- /// </summary>
- /// <typeparam name="T">实体类型</typeparam>
- /// <param name="newt">实体对象,主键不能缺少</param>
- /// <returns></returns>
- public static int UpdateEntity<T>(T newt)
- {
- string TableName = typeof(T).Name;
- PropertyInfo[] plist = typeof(T).GetProperties();
- var type = typeof(T);
- var keyProperties = KeyPropertiesCache(type).ToList();
- string condition = "";
- foreach (var item in keyProperties)
- {
- if (!item.PropertyType.IsGenericType)
- condition = item.Name + "=@" + item.Name + " and";
- }
- string field = "";
- foreach (PropertyInfo p in plist)
- {
- if (!p.PropertyType.IsGenericType)
- field += p.Name + ",";
- }
- field = field.Substring(0, field.Length - 1);
- condition = condition.Substring(0, condition.Length - 4);
- T oldt = GetModel<T>(TableName, field, "where 1=1 " + condition, newt);
- if (newt == null || oldt == null) return 0;
- if (newt.Equals(oldt)) return 0;
- string objVal1 = string.Empty;
- string objVal2 = string.Empty;
- string updatestr = "";
- foreach (PropertyInfo p in plist)
- {
- objVal1 = p.GetValue(newt, null) == null ? string.Empty : p.GetValue(newt, null).ToString();
- objVal2 = p.GetValue(oldt, null) == null ? string.Empty : p.GetValue(oldt, null).ToString();
- if (objVal1 != objVal2)
- updatestr += p.Name + "=@" + p.Name + ",";
- }
- updatestr = updatestr.Substring(0, updatestr.Length - 1);
- string sql = "update " + TableName + " set " + updatestr + " where 1=1 " + condition;
- var result = connection.Execute(sql, newt);
- return result;
- }
- /// <summary>
- /// 更新实体,需要旧的实体对象
- /// </summary>
- /// <typeparam name="T">实体类型</typeparam>
- /// <param name="oldt">旧的实体对象</param>
- /// <param name="newt">新的实体对象</param>
- /// <returns></returns>
- public static int UpdateEntity<T>(T oldt, T newt)
- {
- string TableName = typeof(T).Name;
- PropertyInfo[] plist = typeof(T).GetProperties();
- var type = typeof(T);
- var keyProperties = KeyPropertiesCache(type).ToList();
- if (newt == null || oldt == null) return 0;
- if (newt.Equals(oldt)) return 0;
- string objVal1 = string.Empty;
- string objVal2 = string.Empty;
- string updatestr = "";
- foreach (PropertyInfo p in plist)
- {
- objVal1 = p.GetValue(newt, null) == null ? string.Empty : p.GetValue(newt, null).ToString();
- objVal2 = p.GetValue(oldt, null) == null ? string.Empty : p.GetValue(oldt, null).ToString();
- if (objVal1 != objVal2&& !p.PropertyType.IsGenericType)
- updatestr += p.Name + "=@" + p.Name + ",";
- }
- updatestr = updatestr.Substring(0, updatestr.Length - 1);
- string condition = "";
- foreach (var item in keyProperties)
- {
- if (!item.PropertyType.IsGenericType)
- condition = item.Name + "=@" + item.Name + " and";
- }
- condition = condition.Substring(0, condition.Length - 4);
- string sql = "update " + TableName + " set " + updatestr + " where 1=1 " + condition;
- var result = connection.Execute(sql, newt);
- return result;
- }
- #endregion
- #region 删除记录
- /// <summary>
- /// 删除记录
- /// </summary>
- /// <param name="TableName">表名</param>
- /// <param name="WhereString">条件</param>
- /// <param name="Parameters">参数对象</param>
- /// <returns></returns>
- public static int Delete(string TableName, string WhereString, object Parameters = null)
- {
- string sql = "delete from " + TableName + " where 1=1 " + WhereString;
- var result = connection.Execute(sql, Parameters);
- return result;
- }
- /// <summary>
- /// 删除
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static int Delete(PageCriteria criteria, object Parameters = null)
- {
- string sql = "delete from " + criteria.TableName + " where 1=1 " + criteria.Condition;
- var result = connection.Execute(sql, Parameters);
- return result;
- }
- #endregion
- #region 查询操作
- /// <summary>
- /// 查询返回DataSet
- /// </summary>
- /// <param name="TableName"></param>
- /// <param name="FieldString"></param>
- /// <param name="WhereString"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static DataSet QueryGetDS(string TableName, string FieldString, string WhereString, object Parameters = null)
- {
- DataSet ds = new XDataSet();
- string sql = "select " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
- var result = connection.ExecuteReader(sql, Parameters);
- try
- {
- ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
- }
- finally { result.Close(); }
- return ds;
- }
- /// <summary>
- /// 查询返回DataSet
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static DataSet QueryGetDS(PageCriteria criteria, object Parameters = null)
- {
- DataSet ds = new XDataSet();
- string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
- var result = connection.ExecuteReader(sql, Parameters);
- try
- {
- ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
- }
- finally { result.Close(); }
- return ds;
- }
- /// <summary>
- /// 查询返回DataTable
- /// </summary>
- /// <param name="TableName"></param>
- /// <param name="FieldString"></param>
- /// <param name="WhereString"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static DataTable QueryGetDT(string TableName, string FieldString, string WhereString, object Parameters = null)
- {
- DataTable dt = new DataTable();
- string sql = "select " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
- var result = connection.ExecuteReader(sql, Parameters);
- try
- {
- dt.Load(result);
- }
- finally { result.Close(); }
- return dt;
- }
- /// <summary>
- /// 查询返回DataTable
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static DataTable QueryGetDT(PageCriteria criteria, object Parameters = null)
- {
- DataTable dt = new DataTable();
- string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
- var result = connection.ExecuteReader(sql, Parameters);
- try
- {
- dt.Load(result);
- }
- finally { result.Close(); }
- return dt;
- }
- /// <summary>
- /// 查询查询返回list
- /// </summary>
- /// <param name="TableName"></param>
- /// <param name="FieldString"></param>
- /// <param name="WhereString"></param>
- /// <param name="Parameters"></param>
- /// <returns>对象集</returns>
- public static List<T> Query<T>(string TableName, string FieldString, string WhereString, object Parameters = null)
- {
- string sql = "select " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
- var result = connection.Query<T>(sql, Parameters).ToList();
- return result;
- }
- /// <summary>
- /// 查询返回list
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static List<T> Query<T>(PageCriteria criteria, object Parameters = null)
- {
- string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
- var result = connection.Query<T>(sql, Parameters).ToList();
- return result;
- }
- /// <summary>
- /// 获取模型
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="TableName"></param>
- /// <param name="FieldString"></param>
- /// <param name="WhereString"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static T GetModel<T>(string TableName, string FieldString, string WhereString, object Parameters = null)
- {
- string sql = "select top 1 " + FieldString + " from " + TableName + " where 1=1 " + WhereString;
- var result = connection.Query<T>(sql, Parameters).FirstOrDefault();
- return result;
- }
- /// <summary>
- /// 获取模型
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="criteria"></param>
- /// <param name="Parameters"></param>
- /// <returns></returns>
- public static T GetModel<T>(PageCriteria criteria, object Parameters = null)
- {
- string sql = "select " + criteria.Fields + " from " + criteria.TableName + " where 1=1 " + criteria.Condition;
- var result = connection.Query<T>(sql, Parameters).FirstOrDefault();
- return result;
- }
- /// <summary>
- /// 获取实体通过实体
- /// </summary>
- /// <typeparam name="T">实体类型</typeparam>
- /// <param name="t">实体对象</param>
- /// <param name="condition">and field1=@field1 and field2=@field2</param>
- /// <returns></returns>
- public static T GetModel<T>(T t, string condition=null)
- {
- string TableName = typeof(T).Name;
- PropertyInfo[] plist = typeof(T).GetProperties();
- var type = typeof(T);
- var keyProperties = KeyPropertiesCache(type).ToList();
- if (string.IsNullOrEmpty(condition)){
- foreach (var item in keyProperties)
- {
- if (!item.PropertyType.IsGenericType)
- condition =" and " + item.Name + "=@" + item.Name ;
- }
- }
- string field = "";
- foreach (PropertyInfo p in plist)
- {
- if (!p.PropertyType.IsGenericType)
- field += p.Name + ",";
- }
- field = field.Substring(0, field.Length - 1);
- string sql = "select top 1 " + field + " from " + TableName + " where 1=1 " + condition;
- var result = connection.Query<T>(sql, t).FirstOrDefault();
- return result;
- }
- /// <summary>
- /// 通用分页获取数据
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="criteria"></param>
- /// <param name="param"></param>
- /// <returns></returns>
- public static PageDataView<T> GetPageModelList<T>(PageCriteria criteria)
- {
- var p = new DynamicParameters();
- string proName = "Fgly_Public_Pagination";
- p.Add("TableName", criteria.TableName);
- p.Add("PrimaryKey", criteria.PrimaryKey);
- p.Add("Fields", criteria.Fields);
- p.Add("Filter", criteria.Condition);
- p.Add("CurrentPage", criteria.CurrentPage);
- p.Add("PageSize", criteria.PageSize);
- p.Add("Order", criteria.Sort);
- p.Add("TotalCount", dbType: DbType.Int32, direction: ParameterDirection.Output);
- connection.Open();
- var pageData = new PageDataView<T>
- {
- Items = connection.Query<T>(proName, p, commandType: CommandType.StoredProcedure).ToList()
- };
- connection.Close();
- pageData.TotalNum = p.Get<int>("TotalCount");
- pageData.TotalPageCount = Convert.ToInt32(Math.Ceiling(pageData.TotalNum * 1.0 / criteria.PageSize));
- pageData.CurrentPage = criteria.CurrentPage > pageData.TotalPageCount ? pageData.TotalPageCount : criteria.CurrentPage;
- return pageData;
- }
- /// <summary>
- /// 分页获取数据
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="TotalCount"></param>
- /// <returns></returns>
- public static DataTable GetPageProc(PageCriteria criteria,ref int TotalCount)
- {
- var p = new DynamicParameters();
- string proName = "Fgly_Public_Pagination";
- p.Add("TableName", criteria.TableName);
- p.Add("PrimaryKey", criteria.PrimaryKey);
- p.Add("Fields", criteria.Fields);
- p.Add("Filter", criteria.Condition);
- p.Add("CurrentPage", criteria.CurrentPage);
- p.Add("PageSize", criteria.PageSize);
- p.Add("Order", criteria.Sort);
- p.Add("TotalCount", dbType: DbType.Int32, direction: ParameterDirection.Output);
- DataTable dt = new DataTable();
- //connection.Open();
- var result = connection.ExecuteReader(proName, p, commandType: CommandType.StoredProcedure);
- try
- {
- dt.Load(result);
- }
- finally { result.Close(); }
- connection.Close();
- TotalCount = p.Get<int>("TotalCount");
- return dt;
- }
- /// <summary>
- /// 分页获取数据
- /// </summary>
- /// <param name="criteria"></param>
- /// <param name="TotalCount"></param>
- /// <returns></returns>
- public static IList<T> GetPageProc<T>(PageCriteria criteria, ref int TotalCount)
- {
- var p = new DynamicParameters();
- string proName = "Fgly_Public_Pagination";
- p.Add("TableName", criteria.TableName);
- p.Add("PrimaryKey", criteria.PrimaryKey);
- p.Add("Fields", criteria.Fields);
- p.Add("Filter", criteria.Condition);
- p.Add("CurrentPage", criteria.CurrentPage);
- p.Add("PageSize", criteria.PageSize);
- p.Add("Order", criteria.Sort);
- p.Add("TotalCount", dbType: DbType.Int32, direction: ParameterDirection.Output);
- connection.Open();
- var result = connection.Query<T>(proName, p, commandType: CommandType.StoredProcedure).ToList();
- connection.Close();
- TotalCount = p.Get<int>("TotalCount");
- return result;
- }
- #endregion
- #region 执行存储过程
- /// <summary>
- /// 执行存储过程并返回List
- /// </summary>
- /// <param name="proName"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static List<T> ExtProcGetList<T>(string proName, object p = null)
- {
- var result = connection.Query<T>(proName, p, commandType: CommandType.StoredProcedure).ToList();
- return result;
- }
- /// <summary>
- /// 执行存储过程并返回DataSet
- /// </summary>
- /// <param name="proName"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static DataSet ExtProcGetDS(string proName, object p=null)
- {
- DataSet ds = new XDataSet();
- var result = connection.ExecuteReader(proName, p, commandType: CommandType.StoredProcedure);
- try
- {
- ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
- }
- finally { result.Close(); }
- return ds;
- }
- /// <summary>
- /// 执行存储过程并返回DataTable
- /// </summary>
- /// <param name="proName"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static DataTable ExtProcGetDT(string proName, object p = null)
- {
- DataTable dt = new DataTable();
- var result = connection.ExecuteReader(proName, p, commandType: CommandType.StoredProcedure);
- try
- {
- dt.Load(result);
- }
- finally { result.Close(); }
- return dt;
- }
- /// <summary>
- /// 执行存储过程返回受影响的行数
- /// </summary>
- /// <param name="proName"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static int IntExtProc(string proName,object p = null)
- {
- int result = connection.Execute(proName, p, commandType: CommandType.StoredProcedure);
- return result;
- }
- /// <summary>
- /// 执行存储过程返回一个值
- /// </summary>
- /// <param name="proName"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static object ExtProcScale(string proName, object p = null)
- {
- object result = connection.ExecuteScalar(proName, p, commandType: CommandType.StoredProcedure);
- return result;
- }
- #endregion
- #region 执行Sql语句
- /// <summary>
- /// 执行sql返回list
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="sql"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static List<T> ExtSqlGetList<T>(string sql,object p = null)
- {
- var result = connection.Query<T>(sql, p).ToList();
- return result;
- }
- /// <summary>
- /// 执行Sql语句返回模型
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="sql"></param>
- /// <param name="parameter"></param>
- /// <returns></returns>
- public static T ExtSqlGetModel<T>(string sql, object parameter)
- {
- var result = connection.Query<T>(sql, parameter).ToList().FirstOrDefault();
- return result;
- }
- /// <summary>
- /// 执行sql返回DataSet
- /// </summary>
- /// <param name="sql"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static DataSet ExtSqlGetDS(string sql,object p = null)
- {
- DataSet ds = new XDataSet();
- var result = connection.ExecuteReader(sql, p);
- try
- {
- ds.Load(result, LoadOption.OverwriteChanges, null, new DataTable[] { });
- }
- finally { result.Close(); }
- return ds;
- }
- /// <summary>
- /// 执行SQL返回DataTable
- /// </summary>
- /// <param name="sql"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static DataTable ExtSqlGetDT(string sql, object p = null)
- {
- DataTable dt = new DataTable();
- var result = connection.ExecuteReader(sql, p);
- try
- {
- dt.Load(result);
- }
- finally { result.Close(); }
- return dt;
- }
- /// <summary>
- /// 执行SQL返回受影响的行数
- /// </summary>
- /// <param name="sql"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static int IntExtSql(string sql, object p = null)
- {
- int result = connection.Execute(sql, p);
- return result;
- }
- /// <summary>
- /// 执行SQL返回一个值
- /// </summary>
- /// <param name="sql"></param>
- /// <param name="p"></param>
- /// <returns></returns>
- public static object ExtSqlScale(string sql,object p = null)
- {
- object result = connection.ExecuteScalar(sql, p);
- return result;
- }
- #endregion
- #region 扩展需要方法
- private static List<PropertyInfo> KeyPropertiesCache(Type type)
- {
- var allProperties = TypePropertiesCache(type);
- var keyProperties = allProperties.Where(p => p.GetCustomAttributes(true).Any(a => a is Dapper.Contrib.Extensions.KeyAttribute)).ToList();
- if (keyProperties.Count == 0)
- {
- var idProp = allProperties.Find(p => string.Equals(p.Name, "id", StringComparison.CurrentCultureIgnoreCase));
- if (idProp != null && !idProp.GetCustomAttributes(true).Any(a => a is ExplicitKeyAttribute))
- {
- keyProperties.Add(idProp);
- }
- }
- KeyProperties[type.TypeHandle] = keyProperties;
- return keyProperties;
- }
- private static List<PropertyInfo> TypePropertiesCache(Type type)
- {
- var properties = type.GetProperties().Where(IsWriteable).ToArray();
- TypeProperties[type.TypeHandle] = properties;
- return properties.ToList();
- }
- private static bool IsWriteable(PropertyInfo pi)
- {
- var attributes = pi.GetCustomAttributes(typeof(WriteAttribute), false).AsList();
- if (attributes.Count != 1) return true;
- var writeAttribute = (WriteAttribute)attributes[0];
- return writeAttribute.Write;
- }
- #endregion
- }
- public class XLoadAdapter : DataAdapter
- {
- public XLoadAdapter()
- {
- }
- public int FillFromReader(DataSet ds, IDataReader dataReader, int startRecord, int maxRecords)
- {
- return this.Fill(ds, "Table", dataReader, startRecord, maxRecords);
- }
- }
- public class XDataSet : DataSet
- {
- public override void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler handler, params DataTable[] tables)
- {
- XLoadAdapter adapter = new XLoadAdapter
- {
- FillLoadOption = loadOption,
- MissingSchemaAction = MissingSchemaAction.AddWithKey
- };
- if (handler != null)
- {
- adapter.FillError += handler;
- }
- adapter.FillFromReader(this, reader, 0, 0);
- if (!reader.IsClosed && !reader.NextResult())
- {
- reader.Close();
- }
- }
- }
- }
这个类,包含了对实体操作,执行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拓展及数据库生成实体的更多相关文章
- VS2015 +EF6 连接MYSQL数据库生成实体
VS2015 +EF6 连接MYSQL数据库生成实体 已安装软件:VS2015 XAMPP Control Panel(Mysql服务器) ...
- NetCore +EF+Mysql 从数据库生成实体类到项目
1.点击“工具”->“NuGet包管理器”->“程序包管理器控制台” 分别安装以下几个包 Mysql 版本: Install-Package MySql.Data.EntityFramew ...
- NetCore +EFCore+SqlServer根据数据库生成实体类到项目中
转载自:https://www.cnblogs.com/yangjinwang/p/9516988.html 1.点击“工具”->“NuGet包管理器”->“程序包管理器控制台” 分别安装 ...
- .net core 根据数据库生成实体类
微软最近几年在跨平台上不断发力,很多.net程序员也摩拳擦掌,对微软寄以厚望.就在最近,微软还推出了asp .net core2.0预览版. 通过对.net core的简单尝试,我发现以往我们开发MV ...
- 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 ...
- VS根据数据库生成实体类
一.在类库项目上添加新项 二. 三.依次填入数据库连接 选择数据库 就可以生成数据库实体
- .Net Core 从MySql数据库生成实体类 Entity Model
1.首先建测试库 2.新建一个.Net Core 项目 3. cd到项目里面执行命令: dotnet add package MySql.Data.EntityFrameworkCore 4.继续执行 ...
- idea如何通过数据库生成实体类
---恢复内容开始--- https://blog.csdn.net/liu_yulong/article/details/72910588 ---恢复内容结束---
- 在eclipse中生成实体类
1.在eclipse的windows中选中preferences在查询框中输入driver definition 2.点击add在Name/type中选中mysql jdbc driver 5.1然后 ...
随机推荐
- 第四章 JavaScript操作DOM对象
第四章 JavaScript操作DOM对象 一.DOM操作 DOM是Document Object Model的缩写,即文档对象模型,是基于文档编程的一套API接口,1988年,W3C发布了第一级 ...
- linux——网络基础
装完linux系统要对网络(ip地址,子网掩码,网关,DNS)进行配置,才能连接网络 一,开启网卡eth0 CentOS显示没有网卡(eth0) 2.设置静态IP vim /etc/sysconfig ...
- RSA的公钥、私钥
一.举个例子 1.发消息 用对方的公钥给对方发消息 2.发公告 发公告的时候,用自己的私钥形成签名! 二.加密和签名 RSA的公钥.私钥是互相对应的,RSA会生成两个密钥,你可以把任何一个用于公钥,然 ...
- spring-oauth-server实践:使用授权方式四:client_credentials 模式的客户端和服务端交互
spring-oauth-server入门(1-11)使用授权方式四:client_credentials 模式的客戶端 一.客户端逻辑 1.界面入口(credentials_access_token ...
- Spark入门(1-1)什么是spark,spark和hadoop
一.Spark是什么? Apache Spark 是专为大规模数据处理而设计的快速通用的计算引擎,可用来构建大型的.低延迟的数据分析应用程序. Spark是UC Berkeley AMP lab (加 ...
- linux下mongodb安装、服务器、客户端、备份、账户命令
在linux环境安装mongoDB: 一般认为偶数版本为稳定版 如 1.6.x,奇数版本为开发版如1.7.x 32bit的mongoDB最大能存放2g的数据,64bit没有限制 方法1: 终端执行: ...
- monogodb3.4安装修改,权限设置
下载地址:https://www.mongodb.com/download-center#community 这里的方法只对应3.4,别的有没有效果请自行判断. 下载后按默认下一步. 默认安装地址 ...
- SQL Server 2008 R2 安装注意事项
上个星期自己第一次安装SQL Server 2008 R2,安装失败几次,结果用了将近1天的时间安装,最后成功了. 心得:1.安装SQL Server 2008 R2时,最好在第一次就安装成功.在百度 ...
- Java面试题2--数据类型
1. Java的数据类型? 2. Java的封装类型? 3. 基本类型和封装类型的区别? 基本类型只能按值传递,而对应的封装类是按引用传递的. 基本类型是在堆栈上创建的,而所有的对象类型都是在堆上创建 ...
- iframe 里的高度自适应
由于公司里的很多东西都要用到iframe 导致我不得不各种百度 首先是自适应高度 // document.domain = "caibaojian.com"; function s ...