C# Dapper 简单实例
?
/// <summary>?
/// 分頁信息/// </summary>public class PageInfo<T>{/// <summary>/// 分頁信息/// </summary>public PageInfo(){}/// <summary>/// 總頁數(shù)/// </summary>public long TotalCount{get; set;}/// <summary>///?/// </summary>public IEnumerable<T> Data{get; set;}/// <summary>///?/// </summary>/// <param name="total"></param>/// <param name="data"></param>public PageInfo(long total, IEnumerable<T> data){this.TotalCount = total;this.Data = data;}}*************?
using DapperExtensions.Mapper;
using Statistics.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowStatistics
{
??? public static class Mappings
??? {
??????? public static void Initialize()
??????? {
??????????? DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>);
??????????? DapperExtensions.DapperExtensions.SetMappingAssemblies(new[]
??????????? {
??????????????? typeof(Mappings).Assembly
??????????? });
??????? }
??????? public class FlowCellMapper : ClassMapper<FlowCell>
??????? {
??????????? public FlowCellMapper()
??????????? {
??????????????? Table("jxc_flow_cell");
??????????????? //Map(fcel => fcel.id).Column("id");
??????????????? //Map(fcel => fcel.parent_id).Column("parent_id");
??????????????? //Map(fcel => fcel.create_time).Column("create_time");
??????????????? //Map(fcel => fcel.type_id).Column("type_id");
??????????????? Map(fcel => fcel.comId).Column("bloc_code");
??????????????? //Map(fcel => fcel.bloc_name).Column("bloc_name");
??????????????? //Map(fcel => fcel.cell_number).Column("cell_number");
??????????????? //Map(fcel => fcel.name).Column("name");
??????????????? //Map(fcel => fcel.flows).Column("flows");
??????????????? //Map(fcel => fcel.status).Column("status");
??????????????? //Map(fcel => fcel.del).Column("del");
??????????????? AutoMap();
??????????? }
??????? }
??? }
}
?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using DapperExtensions;
using DapperExtensions.Sql;
using MySql.Data.MySqlClient;
using System.Data;
using Z.Dapper.Plus;
namespace FlowStatistics
{
??? /// <summary>
??? /// 數(shù)據(jù)客戶端
??? /// 參考:https://github.com/StackExchange/dapper-dot-net
??? /// Predicates參考:https://github.com/tmsmith/Dapper-Extensions/wiki/Predicates
??? /// https://github.com/zzzprojects/Dapper-Plus
??? /// </summary>
??? public class DbClient : IDisposable, IDbClient
??? {
??????? string connStr = @"Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True;uid=sa;pwd=123456";??????
??????? int commandTimeout = 30;
??????? /// <summary>
??????? /// 數(shù)據(jù)客戶端
??????? /// </summary>
??????? /// <param name="connStr">數(shù)據(jù)庫連接字符串</param>
??????? /// <param name="dbType">數(shù)據(jù)庫類型</param>
??????? /// <param name="commandTimeout">操作超時(shí),單位:秒</param>
??????? /// <param name="autoEditEntityTime">是否自動(dòng)更實(shí)體對(duì)象的創(chuàng)建時(shí)間、更新時(shí)間</param>
??????? public DbClient(string connStr, int commandTimeout = 30)
??????? {
??????????? if (string.IsNullOrWhiteSpace(connStr)) throw new NoNullAllowedException("數(shù)據(jù)庫連接字符串不允許為空");
??????????? this.connStr = connStr;
??????????? this.commandTimeout = commandTimeout;
??????????? DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect();
??????????? Mappings.Initialize();
??????????? //DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);
??????? }
??????? /// <summary>
??????? /// 獲取打開的連接
??????? /// </summary>
??????? /// <param name="mars">MSSql數(shù)據(jù)庫下有效:如果為 true,則應(yīng)用程序可以保留多活動(dòng)結(jié)果集 (MARS)。 如果為 false,則應(yīng)用程序必須處理或取消一個(gè)批處理中的所有結(jié)果集,然后才能對(duì)該連接執(zhí)行任何其他批處理。</param>
??????? /// <returns></returns>
??????? public IDbConnection GetOpenConnection()
??????? {
??????????? IDbConnection connection = null;
??????????? string cs = connStr;
??????????? connection = new MySqlConnection(cs);
??????????? connection.Open();
??????????? return connection;
??????? }
??????? #region Add
??????? /// <summary>
??????? /// 批量新增
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="entities">實(shí)體對(duì)象集</param>
??????? public void Add<T>(IEnumerable<T> entities) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? using (var trans = cnn.BeginTransaction())
??????????????? {
??????????????????? try
??????????????????? {
??????????????????????? cnn.Insert(entities, trans, commandTimeout);
??????????????????? }
??????????????????? catch (DataException ex)
??????????????????? {
??????????????????????? trans.Rollback();
??????????????????????? throw ex;
??????????????????? }
??????????????????? trans.Commit();
??????????????? }
??????????? }
??????????? //using (IDbConnection cnn = GetOpenConnection())
??????????? //{
??????????? //??? var trans = cnn.BeginTransaction();
??????????? //??? cnn.Execute(@"insert Member(Username, IsActive) values(@Username, @IsActive)", entities, transaction: trans);
??????????? //??? trans.Commit();
??????????? //}
??????? }
??????? /// <summary>
??????? /// 新增
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="entity">實(shí)體對(duì)象</param>
??????? /// <returns>實(shí)體對(duì)象</returns>
??????? public T Add<T>(T entity) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? T res = null;
??????????????? using (var trans = cnn.BeginTransaction())
??????????????? {
??????????????????? try
??????????????????? {
??????????????????????? int id = cnn.Insert(entity, trans, commandTimeout);
??????????????????????? if (id > 0)
??????????????????????? {
??????????????????????????? res = entity;
??????????????????????? }
??????????????????? }
??????????????????? catch (DataException ex)
??????????????????? {
??????????????????????? trans.Rollback();
??????????????????????? throw ex;
??????????????????? }
??????????????????? trans.Commit();
??????????????? }
??????????????? return res;
??????????? }
??????? }
???????
??????? #endregion
??????? #region Update
??????? /// <summary>
??????? /// 更新
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="entity">實(shí)體對(duì)象</param>
??????? /// <returns>是否成功</returns>
??????? public bool Update<T>(T entity) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? bool res = false;
??????????????? using (var trans = cnn.BeginTransaction())
??????????????? {
??????????????????? try
??????????????????? {
??????????????????????? res = cnn.Update(entity, trans, commandTimeout);
??????????????????? }
??????????????????? catch (DataException ex)
??????????????????? {
??????????????????????? trans.Rollback();
??????????????????????? throw ex;
??????????????????? }
??????????????????? trans.Commit();
??????????????? }
??????????????? return res;
??????????? }
??????? }
??????? public bool Update<T>(IEnumerable<T> entities) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? bool res = false;
??????????????? using (var trans = cnn.BeginTransaction())
??????????????? {
??????????????????? try
??????????????????? {
??????????????????????? trans.BulkUpdate(entities);
??????????????????????? res = true;
??????????????????? }
??????????????????? catch (DataException ex)
??????????????????? {
??????????????????????? trans.Rollback();
??????????????????????? throw ex;
??????????????????? }
??????????????????? trans.Commit();
??????????????? }
??????????????? return res;
??????????? }
??????? }
??????? #endregion
??????? #region Delete
??????? /// <summary>
??????? /// 刪除
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="entity">實(shí)體對(duì)象</param>
??????? /// <returns>是否成功</returns>
??????? public bool Delete<T>(T entity) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? bool res = false;
??????????????? using (var trans = cnn.BeginTransaction())
??????????????? {
??????????????????? try
??????????????????? {
??????????????????????? res = cnn.Delete(entity, trans, commandTimeout);
??????????????????? }
??????????????????? catch (DataException ex)
??????????????????? {
??????????????????????? trans.Rollback();
??????????????????????? throw ex;
??????????????????? }
??????????????????? trans.Commit();
??????????????? }
??????????????? return res;
??????????? }
??????? }
??????? /// <summary>
??????? /// 條件刪除
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="predicate">實(shí)體對(duì)象</param>
??????? /// <returns>是否成功</returns>
??????? public bool Delete<T>(object predicate) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? bool res = false;
??????????????? using (var trans = cnn.BeginTransaction())
??????????????? {
??????????????????? try
??????????????????? {
??????????????????????? res = cnn.Delete(predicate, trans, commandTimeout);
??????????????????? }
??????????????????? catch (DataException ex)
??????????????????? {
??????????????????????? trans.Rollback();
??????????????????????? throw ex;
??????????????????? }
??????????????????? trans.Commit();
??????????????? }
??????????????? return res;
??????????? }
??????? }
??????? #endregion
??????? #region Query/Get
??????? /// <summary>
??????? /// 查詢單個(gè)結(jié)果
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="id">實(shí)體的Id屬性值</param>
??????? /// <returns>查詢結(jié)果</returns>
??????? public T Get<T>(object id) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? T res = null;
??????????????? try
??????????????? {
??????????????????? res = cnn.Get<T>(id, null, commandTimeout);
??????????????? }
??????????????? catch (DataException ex)
??????????????? {
??????????????????? throw ex;
??????????????? }
??????????????? return res;
??????????? }
??????? }
??????? /// <summary>
??????? /// 查詢結(jié)果集合
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="predicate">分頁查詢條件</param>
??????? /// <param name="sort">是否排序</param>
??????? /// <returns>查詢結(jié)果</returns>
??????? public IEnumerable<T> Get<T>(object predicate = null, IList<ISort> sort = null) where T : class, new()
??????? {
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? IEnumerable<T> res = null;
??????????????? try
??????????????? {
??????????????????? res = cnn.GetList<T>(predicate, sort, null, commandTimeout);
??????????????? }
??????????????? catch (DataException ex)
??????????????? {
??????????????????? throw ex;
??????????????? }
??????????????? return res;
??????????? }
??????? }
??????? /// <summary>
??????? /// 查詢結(jié)果分頁
??????? /// </summary>
??????? /// <typeparam name="T">實(shí)體類型</typeparam>
??????? /// <param name="predicate">分頁查詢條件</param>
??????? /// <param name="sort">是否排序</param>
??????? /// <param name="pageIndex">分頁索引</param>
??????? /// <param name="pageSize">分頁大小</param>
??????? /// <returns>查詢結(jié)果</returns>
??????? public PageInfo<T> Get<T>(object predicate, IList<ISort> sort, int pageIndex, int pageSize) where T : class, new()
??????? {
??????????? if (sort == null) throw new ArgumentNullException("sort 不允許為null");
??????????? if (pageIndex < 0) pageIndex = 0;
??????????? using (IDbConnection cnn = GetOpenConnection())
??????????? {
??????????????? PageInfo<T> pInfo = null;
??????????????? try
??????????????? {
??????????????????? int count = cnn.Count<T>(predicate, null, commandTimeout);
??????????????????? pInfo = new PageInfo<T>();
??????????????????? pInfo.TotalCount = count;
??????????????????? pInfo.Data = cnn.GetPage<T>(predicate, sort, pageIndex, pageSize, null, commandTimeout);
??????????????? }
??????????????? catch (DataException ex)
??????????????? {
??????????????????? throw ex;
??????????????? }
??????????????? return pInfo;
??????????? }
??????? }
??????? #endregion
??????? #region IDisposable Support
??????? private bool disposedValue = false; // 要檢測(cè)冗余調(diào)用
??????? protected virtual void Dispose(bool disposing)
??????? {
??????????? if (!disposedValue)
??????????? {
??????????????? if (disposing)
??????????????? {
??????????????????? // TODO: 釋放托管狀態(tài)(托管對(duì)象)。
??????????????? }
??????????????? // TODO: 釋放未托管的資源(未托管的對(duì)象)并在以下內(nèi)容中替代終結(jié)器。
??????????????? // TODO: 將大型字段設(shè)置為 null。
??????????????? disposedValue = true;
??????????? }
??????? }
??????? // TODO: 僅當(dāng)以上 Dispose(bool disposing) 擁有用于釋放未托管資源的代碼時(shí)才替代終結(jié)器。
??????? // ~DbClient() {
??????? //?? // 請(qǐng)勿更改此代碼。將清理代碼放入以上 Dispose(bool disposing) 中。
??????? //?? Dispose(false);
??????? // }
??????? // 添加此代碼以正確實(shí)現(xiàn)可處置模式。
??????? void IDisposable.Dispose()
??????? {
??????????? // 請(qǐng)勿更改此代碼。將清理代碼放入以上 Dispose(bool disposing) 中。
??????????? Dispose(true);
??????????? // TODO: 如果在以上內(nèi)容中替代了終結(jié)器,則取消注釋以下行。
??????????? // GC.SuppressFinalize(this);
??????? }
??????? #endregion
??? }
}
public class FlowCell
??? {
??????? public int Id { get; set; }
??????? public int type_id { get; set; }
??????? public string comId { get; set; }
??????? public string bloc_name { get; set; }
??????? public string cell_number { get; set; }
??????? public string name { get; set; }
??????? public int flows { get; set; }?????
??????? public int status { get; set; }??????
??????? public int del { get; set; }
??? }
使用:
public void Statistics()
??????? {
??????????? try
??????????? {
??????????????? DbClient dbClient = new DbClient(mysqlConstr);
??????????????? var pg = new PredicateGroup { Operator = GroupOperator.Or, Predicates = new List<IPredicate>() };
??????????????? pg.Predicates.Add(Predicates.Field<FlowCell>(f => f.status, Operator.Eq, 1));
??????????????? pg.Predicates.Add(Predicates.Field<FlowCell>(f => f.del, Operator.Eq, 0));
??????????????? var flowCell = dbClient.Get<FlowCell>(4);
??????????????? IList<ISort> sorts = new List<ISort>();
??????????????? ISort sort = new Sort();
??????????????? sort.Ascending = false;
??????????????? sort.PropertyName = "name"; //如果有Map,則此次要填寫Map對(duì)象的字段名稱,而不是數(shù)據(jù)庫表字段名稱
??????????????? sorts.Add(sort);
??????????????? var flowCell2 = dbClient.Get<FlowCell>(pg, sorts);
??????????????? var flowCell3 = dbClient.Get<FlowCell>(pg, sorts, 0, 2);
??????????? }
??????????? catch (Exception ex)
??????????? {
??????????? }
??????? }
總結(jié)
以上是生活随笔為你收集整理的C# Dapper 简单实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到刮大风房子倒是什么意思啊
- 下一篇: 女人梦到看见水里有甲鱼什么预兆