Dapper 基本使用
项目下引用右键->管理NuGet程序包->浏览,搜索Dapper
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
-
- namespace Dapper.Repository
- {
- public class DapperDemo
- {
- public static string ConnectionString
- {
- get
- {
- string _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
- return _connectionString;
- }
- }
-
- public SqlConnection OpenConnection()
- {
- SqlConnection connection = new SqlConnection(ConnectionString);
- connection.Open();
- return connection;
- }
-
-
-
-
-
- public bool Add()
- {
- int row = 0;
- ED_Data model = new ED_Data();
- model.TableName = "123";
- model.DataKey = "123";
- model.FieldName = "123";
- model.Value = "123";
- model.Reference = "123";
- model.Branch = 1;
- model.InActive = false;
- model.Updated = DateTime.Now;
-
- string query = "INSERT INTO ED_Data(TableName,DataKey,FieldName,Value,Reference,Branch,InActive,Updated) VALUES (@TableName,@DataKey,@FieldName,@Value,@Reference,@Branch,@InActive,@Updated)";
- using (IDbConnection conn = OpenConnection())
- {
- row = conn.Execute(query, model);
- }
- if (row > 0)
- return true;
- else
- return false;
- }
-
-
-
-
-
- public int Update()
- {
- int row = 0;
- ED_Data model = new ED_Data();
- model.TableName = "123";
- model.DataKey = "123";
- model.Updated = DateTime.Now;
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "UPDATE ED_Data SET DataKey=@DataKey,Updated=@Updated WHERE TableName=@TableName";
- row = conn.Execute(query, model);
- }
- return row;
- }
-
-
-
-
-
- public int Delete()
- {
- int row = 0;
- ED_Data model = new ED_Data();
- model.TableName = "123";
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "DELETE FROM ED_Data WHERE TableName=@TableName";
- row = conn.Execute(query, model);
- }
- return row;
- }
-
-
-
-
-
-
- public ED_Data GetModel(string TableName)
- {
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "SELECT * FROM ED_Data WHERE TableName = @TableName";
- return conn.Query<ED_Data>(query, new { tableName = TableName }).SingleOrDefault<ED_Data>();
- }
- }
-
-
-
-
-
- public List<ED_Data> GetED_DataList()
- {
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "SELECT * FROM ED_Data";
- return conn.Query<ED_Data>(query, null).ToList();
- }
- }
-
-
-
-
-
-
-
- public int DeleteColumnCatAndColumn(ED_Data cat)
- {
- try
- {
- using (IDbConnection conn = OpenConnection())
- {
- string delete1 = "DELETE FROM ED_Data WHERE TableName=@TableName";
- string delete2 = "DELETE FROM ED_Data WHERE TableName=@TableName";
-
- IDbTransaction transaction = conn.BeginTransaction();
- int row = conn.Execute(delete1, new { TableName = cat.TableName }, transaction, null, null);
- row += conn.Execute(delete2, new { TableName = cat.TableName }, transaction, null, null);
- transaction.Commit();
- return row;
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
- public void ExecuteStoredProcedure()
- {
- try
- {
- DynamicParameters para = new DynamicParameters();
- para.Add("@param1", 1);
- para.Add("@param2", 2);
-
- using (IDbConnection conn = OpenConnection())
- {
- int row = conn.Execute("存储过程名称", para, null, null, CommandType.StoredProcedure);
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
- public void InsertBatch()
- {
- try
- {
- string sqlStr = "INSERT INTO ED_Data(TableName,DataKey,FieldName,Value,Reference,Branch,InActive,Updated) VALUES (@TableName,@DataKey,@FieldName,@Value,@Reference,@Branch,@InActive,@Updated)";
- using (IDbConnection conn = OpenConnection())
- {
- conn.Execute(sqlStr, new[]
- {
- new { TableName = "user1", DataKey = "a", FieldName = "name", Value = "000001", Reference = "", Branch = "", InActive = "", Updated = DateTime.Now },
- new { TableName = "user2", DataKey = "b", FieldName = "age", Value = "000002", Reference = "", Branch= "", InActive = "", Updated = DateTime.Now },
- new { TableName = "user3", DataKey = "c", FieldName = "phone", Value = "000003", Reference= "", Branch= "", InActive= "", Updated= DateTime.Now },
- }, null, null, null);
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- }
- sing System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
-
- namespace Dapper.Repository
- {
- public class ED_Data
- {
- public string TableName { get; set; }
-
- public string DataKey { get; set; }
-
- public string FieldName { get; set; }
-
- public string Value { get; set; }
-
- public string Reference { get; set; }
-
- public int Branch { get; set; }
-
- public bool InActive { get; set; }
-
- public DateTime Updated { get; set; }
- }
- }
Base基类
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
-
- namespace Dapper.Repository
- {
- public class DapperDemo
- {
- public static string ConnectionString
- {
- get
- {
- string _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
- return _connectionString;
- }
- }
-
- public SqlConnection OpenConnection()
- {
- SqlConnection connection = new SqlConnection(ConnectionString);
- connection.Open();
- return connection;
- }
-
-
-
-
-
- public bool Add()
- {
- int row = 0;
- ED_Data model = new ED_Data();
- model.TableName = "123";
- model.DataKey = "123";
- model.FieldName = "123";
- model.Value = "123";
- model.Reference = "123";
- model.Branch = 1;
- model.InActive = false;
- model.Updated = DateTime.Now;
-
- string query = "INSERT INTO ED_Data(TableName,DataKey,FieldName,Value,Reference,Branch,InActive,Updated) VALUES (@TableName,@DataKey,@FieldName,@Value,@Reference,@Branch,@InActive,@Updated)";
- using (IDbConnection conn = OpenConnection())
- {
- row = conn.Execute(query, model);
- }
- if (row > 0)
- return true;
- else
- return false;
- }
-
-
-
-
-
- public int Update()
- {
- int row = 0;
- ED_Data model = new ED_Data();
- model.TableName = "123";
- model.DataKey = "123";
- model.Updated = DateTime.Now;
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "UPDATE ED_Data SET DataKey=@DataKey,Updated=@Updated WHERE TableName=@TableName";
- row = conn.Execute(query, model);
- }
- return row;
- }
-
-
-
-
-
- public int Delete()
- {
- int row = 0;
- ED_Data model = new ED_Data();
- model.TableName = "123";
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "DELETE FROM ED_Data WHERE TableName=@TableName";
- row = conn.Execute(query, model);
- }
- return row;
- }
-
-
-
-
-
-
- public ED_Data GetModel(string TableName)
- {
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "SELECT * FROM ED_Data WHERE TableName = @TableName";
- return conn.Query<ED_Data>(query, new { tableName = TableName }).SingleOrDefault<ED_Data>();
- }
- }
-
-
-
-
-
- public List<ED_Data> GetED_DataList()
- {
- using (IDbConnection conn = OpenConnection())
- {
- const string query = "SELECT * FROM ED_Data";
- return conn.Query<ED_Data>(query, null).ToList();
- }
- }
-
-
-
-
-
-
-
- public int DeleteColumnCatAndColumn(ED_Data cat)
- {
- try
- {
- using (IDbConnection conn = OpenConnection())
- {
- string delete1 = "DELETE FROM ED_Data WHERE TableName=@TableName";
- string delete2 = "DELETE FROM ED_Data WHERE TableName=@TableName";
-
- IDbTransaction transaction = conn.BeginTransaction();
- int row = conn.Execute(delete1, new { TableName = cat.TableName }, transaction, null, null);
- row += conn.Execute(delete2, new { TableName = cat.TableName }, transaction, null, null);
- transaction.Commit();
- return row;
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
- public void ExecuteStoredProcedure()
- {
- try
- {
- DynamicParameters para = new DynamicParameters();
- para.Add("@param1", 1);
- para.Add("@param2", 2);
-
- using (IDbConnection conn = OpenConnection())
- {
- int row = conn.Execute("存储过程名称", para, null, null, CommandType.StoredProcedure);
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
- public void InsertBatch()
- {
- try
- {
- string sqlStr = "INSERT INTO ED_Data(TableName,DataKey,FieldName,Value,Reference,Branch,InActive,Updated) VALUES (@TableName,@DataKey,@FieldName,@Value,@Reference,@Branch,@InActive,@Updated)";
- using (IDbConnection conn = OpenConnection())
- {
- conn.Execute(sqlStr, new[]
- {
- new { TableName = "user1", DataKey = "a", FieldName = "name", Value = "000001", Reference = "", Branch = "", InActive = "", Updated = DateTime.Now },
- new { TableName = "user2", DataKey = "b", FieldName = "age", Value = "000002", Reference = "", Branch= "", InActive = "", Updated = DateTime.Now },
- new { TableName = "user3", DataKey = "c", FieldName = "phone", Value = "000003", Reference= "", Branch= "", InActive= "", Updated= DateTime.Now },
- }, null, null, null);
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
-
- namespace Dapper.Repository
- {
- public class ED_Data
- {
- public string TableName { get; set; }
-
- public string DataKey { get; set; }
-
- public string FieldName { get; set; }
-
- public string Value { get; set; }
-
- public string Reference { get; set; }
-
- public int Branch { get; set; }
-
- public bool InActive { get; set; }
-
- public DateTime Updated { get; set; }
- }
- }
Base基类
- using Dapper.CoreLibrary;
- using Dapper.Entity;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Transactions;
-
- namespace Dapper.Repository
- {
- public abstract class RepositoryBase<T> : DbConnectionFactory, IRepositoryBase<T> where T : IEntityBase<T>
- {
- public RepositoryBase(IDbConnection db)
- : base(db)
- { }
-
-
-
-
-
-
- public virtual int Add(T model)
- {
- int result = 0;
- try
- {
- var ps = model.GetType().GetProperties();
- List<string> @colms = new List<string>();
- List<string> @params = new List<string>();
- foreach (var p in ps)
- {
- if (!p.CustomAttributes.Any(x => x.AttributeType == typeof(PrimaryKeyAttribute)) && !p.CustomAttributes.Any(x => x.AttributeType == typeof(DBIgnoreAttribute)))
- {
- @colms.Add(string.Format("[{0}]", p.Name));
- @params.Add(string.Format("@{0}", p.Name));
- }
- }
- var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2}); SELECT @@IDENTITY;", typeof(T).Name, string.Join(", ", @colms), string.Join(", ", @params));
- result = _conn.ExecuteScalar<int>(sql, model);
- }
- catch (Exception ex)
- {
- throw;
- }
- return result;
- }
-
-
-
-
-
- public virtual void Add(List<T> listModel)
- {
- try
- {
- using (var scope = new TransactionScope())
- {
- listModel.ForEach(model =>
- {
- var ps = model.GetType().GetProperties();
- List<string> @colms = new List<string>();
- List<string> @params = new List<string>();
- foreach (var p in ps)
- {
- if (!p.CustomAttributes.Any(x => x.AttributeType == typeof(PrimaryKeyAttribute)) && !p.CustomAttributes.Any(x => x.AttributeType == typeof(DBIgnoreAttribute)))
- {
- @colms.Add(string.Format("[{0}]", p.Name));
- @params.Add(string.Format("@{0}", p.Name));
- }
- }
- var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2}); SELECT @@IDENTITY;", typeof(T).Name, string.Join(", ", @colms), string.Join(", ", @params));
- _conn.ExecuteScalar<int>(sql, model);
- });
- scope.Complete();
- }
- }
- catch (Exception ex)
- {
- }
- }
-
-
-
-
-
-
- public virtual int AddWithGuid(T model)
- {
- int result = 0;
- try
- {
- var ps = model.GetType().GetProperties();
- List<string> @colms = new List<string>();
- List<string> @params = new List<string>();
- foreach (var p in ps)
- {
- if (!p.CustomAttributes.Any(x => x.AttributeType == typeof(DBIgnoreAttribute)))
- {
- @colms.Add(string.Format("[{0}]", p.Name));
- @params.Add(string.Format("@{0}", p.Name));
- }
- }
- var sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2});", typeof(T).Name, string.Join(", ", @colms), string.Join(", ", @params));
- result = _conn.Execute(sql, model);
- }
- catch (Exception ex)
- {
- throw;
- }
- return result;
- }
-
-
-
-
-
- public virtual void Update(T model)
- {
- PropertyInfo pkInfo = null;
- var ps = model.GetType().GetProperties();
- List<string> @params = new List<string>();
- foreach (var p in ps)
- {
- if (p.CustomAttributes.Any(x => x.AttributeType == typeof(DBIgnoreAttribute)))
- {
- continue;
- }
- if (p.CustomAttributes.Any(x => x.AttributeType == typeof(PrimaryKeyAttribute)))
- {
- pkInfo = p;
- }
- else
- {
- @params.Add(string.Format("[{0}]=@{0}", p.Name));
- }
- }
- var sql = string.Format("UPDATE [{0}] SET {1} WHERE [{2}] = @{2}", typeof(T).Name, string.Join(", ", @params), pkInfo.Name);
- _conn.Execute(sql, model);
- }
-
-
-
-
-
- public virtual void Update(List<T> listModel)
- {
- using (var scope = new TransactionScope())
- {
- listModel.ForEach(model =>
- {
- PropertyInfo pkInfo = null;
- var ps = model.GetType().GetProperties();
- List<string> @params = new List<string>();
- foreach (var p in ps)
- {
- if (p.CustomAttributes.Any(x => x.AttributeType == typeof(DBIgnoreAttribute)))
- {
- continue;
- }
- if (p.CustomAttributes.Any(x => x.AttributeType == typeof(PrimaryKeyAttribute)))
- {
- pkInfo = p;
- }
- else
- {
- @params.Add(string.Format("[{0}] = @{0}", p.Name));
- }
- }
- var sql = string.Format("UPDATE [{0}] SET {1} WHERE [{2}] = @{2}", typeof(T).Name, string.Join(", ", @params), pkInfo.Name);
- _conn.Execute(sql, model);
- });
- scope.Complete();
- }
- }
-
-
-
-
-
-
-
- public virtual T GetModel(string primaryValue, string tableName = "")
- {
- try
- {
- string primaryWhere = string.Empty;
- var ps = typeof(T).GetProperties();
- if (string.IsNullOrEmpty(tableName))
- {
- tableName = typeof(T).Name;
- }
- var primary = ps.Single(p => p.CustomAttributes.FirstOrDefault(c => c.AttributeType == typeof(PrimaryKeyAttribute)) != null);
-
- primaryWhere = (string.Format("[{0}] = @primarykey", primary.Name));
-
- var sql = string.Format("SELECT * FROM [{0}] WHERE {1}", tableName, primaryWhere);
-
- return _conn.Query<T>(sql, new { primarykey = primaryValue }).FirstOrDefault();
- }
- catch (Exception)
- {
-
- throw;
- }
- }
-
-
-
-
-
-
-
- public virtual T GetModelQuery(string strWhere, string tableName = "")
- {
- try
- {
- var sql = string.Format("SELECT * FROM [{0}] WHERE {1}", tableName, strWhere);
- return _conn.Query<T>(sql, new { where = strWhere }).FirstOrDefault();
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
-
- public virtual void Delete(string primaryValue)
- {
- try
- {
- string primaryWhere = string.Empty;
- var ps = typeof(T).GetProperties();
- var primary = ps.Single(p => p.CustomAttributes.FirstOrDefault(c => c.AttributeType == typeof(PrimaryKeyAttribute)) != null);
- var sql = string.Format("DELETE FROM [{0}] WHERE {1} = @primarykey", typeof(T).Name, primary.Name);
- _conn.Execute(sql, new { primarykey = primaryValue });
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
-
- public void DeleteStrWhere(string strWhere)
- {
- try
- {
- var sql = string.Format("DELETE FROM [{0}] WHERE {1}", typeof(T).Name, strWhere);
- _conn.Execute(sql);
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
-
-
-
- public virtual List<T> GetList(string strWhere, string tableName = "")
- {
- try
- {
- if (string.IsNullOrEmpty(tableName))
- tableName = typeof(T).Name;
- var sql = string.Format("SELECT * FROM [{0}] " + (strWhere == "" ? "" : " WHERE " + " {1} "), tableName, strWhere);
- return _conn.Query<T>(sql).ToList();
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
-
-
- public virtual PagerListResult<List<T>> GetPageList(PagerRequestParam param)
- {
- PagerListResult<List<T>> result = null;
- List<T> list = new List<T>();
- int pageTotal = 1;
- int recordTotal = 0;
- int startIndex = 1;
- int endIndex = param.PageSize;
- try
- {
- if (param.PageIndex - 1 > 0)
- {
- startIndex = (param.PageIndex - 1 <= 0 ? 1 : param.PageIndex - 1) * param.PageSize + 1;
- endIndex = param.PageIndex * param.PageSize;
- }
-
- if (string.IsNullOrEmpty(param.TableName))
- param.TableName = typeof(T).Name;
- StringBuilder strSql = new StringBuilder();
- strSql.Append("SELECT * FROM ( ");
- strSql.Append(" SELECT ROW_NUMBER() OVER (");
- if (!string.IsNullOrEmpty(param.OrderBy))
- {
- strSql.Append("ORDER BY T." + param.OrderBy);
- }
- else
- {
- strSql.Append("ORDER BY T.ID DESC");
- }
- strSql.Append(")AS Row, T.* FROM " + param.TableName + " T ");
- if (!string.IsNullOrEmpty(param.StrWhere))
- {
- strSql.Append(" WHERE " + param.StrWhere);
- }
- strSql.Append(" ) TT");
- strSql.AppendFormat(" WHERE TT.Row BETWEEN {0} AND {1}", startIndex, endIndex);
-
- list = _conn.Query<T>(strSql.ToString(), param.StrWhere).ToList();
- if (list.Count > 0)
- {
- recordTotal = this.GetRecordCount(param.StrWhere, param.TableName);
- pageTotal = PagerRequestParam.Tool.PageTotal(param);
- }
- result = new PagerListResult<List<T>>(list, pageTotal, recordTotal);
- }
- catch (Exception ex)
- {
- result = new PagerListResult<List<T>>(ex);
- }
- return result;
- }
-
-
-
-
-
-
- public int DeleteTransaction()
- {
- try
- {
- const string delete1 = "DELETE FROM ED_Data WHERE TableName=@TableName";
- const string delete2 = "DELETE FROM ED_Data WHERE TableName=@TableName";
-
- IDbTransaction transaction = _conn.BeginTransaction();
- int row = _conn.Execute(delete1, new { TableName = "user" }, transaction, null, null);
- row += _conn.Execute(delete2, new { TableName = "customer" }, transaction, null, null);
- transaction.Commit();
- return row;
- }
- catch (Exception)
- {
- throw;
- }
- }
-
-
-
-
-
-
- public virtual int GetRecordCount(string strWhere, string tableName = "")
- {
- int count = 0;
- try
- {
- if (string.IsNullOrEmpty(tableName))
- tableName = typeof(T).Name;
- StringBuilder strSql = new StringBuilder();
- strSql.Append("SELECT COUNT(1) FROM " + tableName);
- if (!string.IsNullOrEmpty(strWhere))
- {
- strSql.Append(" WHERE " + strWhere);
- }
- count = _conn.ExecuteScalar<int>(strSql.ToString());
- }
- catch (Exception)
- {
-
- throw;
- }
- return count;
- }
- }
- }