C# Dapper 简单实例

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>
    /// 数据客户端
    /// 参考: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>
        /// 数据客户端
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="dbType">数据库类型</param>
        /// <param name="commandTimeout">操作超时,单位:秒</param>
        /// <param name="autoEditEntityTime">是否自动更实体对象的创建时间、更新时间</param>
        public DbClient(string connStr, int commandTimeout = 30)
        {
            if (string.IsNullOrWhiteSpace(connStr)) throw new NoNullAllowedException("数据库连接字符串不允许为空");
            this.connStr = connStr;
            this.commandTimeout = commandTimeout;
            DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect();
            Mappings.Initialize();
            //DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);
        }
        /// <summary>
        /// 获取打开的连接
        /// </summary>
        /// <param name="mars">MSSql数据库下有效:如果为 true,则应用程序可以保留多活动结果集 (MARS)。 如果为 false,则应用程序必须处理或取消一个批处理中的所有结果集,然后才能对该连接执行任何其他批处理。</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">实体类型</typeparam>
        /// <param name="entities">实体对象集</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">实体类型</typeparam>
        /// <param name="entity">实体对象</param>
        /// <returns>实体对象</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">实体类型</typeparam>
        /// <param name="entity">实体对象</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">实体类型</typeparam>
        /// <param name="entity">实体对象</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">实体类型</typeparam>
        /// <param name="predicate">实体对象</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>
        /// 查询单个结果
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="id">实体的Id属性值</param>
        /// <returns>查询结果</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>
        /// 查询结果集合
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="predicate">分页查询条件</param>
        /// <param name="sort">是否排序</param>
        /// <returns>查询结果</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>
        /// 查询结果分页
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="predicate">分页查询条件</param>
        /// <param name="sort">是否排序</param>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        /// <returns>查询结果</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; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }

        // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
        // ~DbClient() {
        //   // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
        //   Dispose(false);
        // }

        // 添加此代码以正确实现可处置模式。
        void IDisposable.Dispose()
        {
            // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
            Dispose(true);
            // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
            // 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";
                sorts.Add(sort);
                var flowCell2 = dbClient.Get<FlowCell>(pg, sorts);

                var flowCell3 = dbClient.Get<FlowCell>(pg, sorts, 0, 2);
            }
            catch (Exception ex)
            {

            }
        }

时间: 2024-08-08 05:20:30

C# Dapper 简单实例的相关文章

【MySQL】存储过程、游标、循环简单实例

有时候仅凭 sql 语句可能达不到想要的数据操作目的,有可能需要写一些方法体,通过循环判断等操作最终达到目的.那么在数据库里实现这种方法体就需要存储过程了,个人觉得一个带注释的简单实例可以简单粗暴地解决大部分问题,当然要深入学习了解的话还是要看教程文档了,话不多说,上码: [sql] view plain copy create procedure my_procedure() -- 创建存储过程 begin -- 开始存储过程 declare my_id varchar(32); -- 自定义

session 对象的简单实例

一个session对象的简单实例: 1.登录界面:使用简单的html表单提交界面. <%@ page language="java" contentType="text/html; charset=GB18030"    pageEncoding="GB18030"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "ht

javamail发送邮件的简单实例(转)

javamail发送邮件的简单实例 今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题.为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用.呵呵 以下三段代码是我的全部代码,朋友们如果想用,直接复制即可. 第一个类:MailSenderInfo.java package com.util.mail;    /**    * 发送邮件需要使用的基本信息  *author by wangfun http://www.5a520.cn 小说520   */  

AJAX学习整理二之简单实例

做了几个简单的实例,加载txt文本内容.加载xml文件内容,把xml文本内容转换成html表格显示.废话不多说,直接贴代码: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/html"> <head>     <title>通过ajax获取文本内容</title>     <meta charset="utf-8">     <scr

Spring+Struts 2 简单实例报空指针异常

空指针出现于Action注入位置..如果一般错误请检查配置文件. 我出的错误.在于拷贝了之前做的实例中的lib文件夹到这个工程中. 其中有个包为struts2-convention-plugin-2.3.16.3.jar 造成了包识别异常.出现空指针.有类似经历的可以查看,也给大家提个醒.不要一气呵成的导入所有包.容易出现混乱.也不利于大家清楚的认识包和代码的联系. Spring+Struts 2 简单实例报空指针异常,布布扣,bubuko.com

mvc area区域和异步表单,bootstrap简单实例

码农最怕眼高手低 今天来练习mvc Area技术和bootstrap以及异步表单的C#代码实现. 1.area区域架构对于建立复杂业务逻辑很有帮助,由  AreaRegistration.RegisterAllAreas()方法遍历路由表,获得所有注册的路由.参见 建立类库Common,下设一个文件夹BookStore 在其中建立model和controller.(注意引用System.Web.Mvc这个dll) 项目结构如图: 其中book.cs为model模型 namespace Commo

DataGridView重绘painting简单实例

private void dataGridViewX1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex>=0) { Rectangle newRect = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width - 1, e.CellBounds.

jQuery Datatable 实用简单实例

目标: 使用jQuery Datatable构造数据列表,并且增加或者隐藏相应的列,已达到数据显示要求.同时,jQuery Datatable强大的功能支持:排序,分页,搜索等. Query Datatable能良好支持数据完全加载到本地后构建数据列表,排序.分页.搜索等功能就会自带,不需要我们去关心,在此主要说明通过后台动态的加载数据,已达到在大数据面前提高效率的效果. 1. 通过后台进行分页 2. 通过后台进行排序 3. 通过后台进行搜索 具体使用方法: 1. 首先构建我们需要的数据列表,以

Hadoop初学指南(6)--MapReduce的简单实例及分析

本文在上一节的基础上通过一个简单的MR示例对MapReduce的运行流程进行分析. 假设有两行数据,分别是hello you,hello me,我们要统计其中出现的单词以及每个单词出现的次数. 所得的结果为 hello   2 you     1 me      1 (1)大致运行流畅 1.解析成2个<k,v>,分别是<0, hello you><10, hello me>.调用2次map函数. 2.执行map任务 3.map输出后的数据是:<hello,1>