C# Dapper 简单实例

 

/// <summary>

 

/// 分页信息
/// </summary>
public class PageInfo<T>
{
/// <summary>
/// 分页信息
/// </summary>
public PageInfo()
{
}
/// <summary>
/// 总页数
/// </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>
    /// 数据客户端
    /// 参考: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"; //如果有Map,则此次要填写Map对象的字段名称,而不是数据库表字段名称
                sorts.Add(sort);
                var flowCell2 = dbClient.Get<FlowCell>(pg, sorts);

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

            }
        }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/396689.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Angular 星级评分组件

一、需求演变及描述&#xff1a; 1. 有一个“客户对公司的总体评价”的字段&#xff08;evalutation&#xff09;。字段为枚举类型&#xff0c;0-5&#xff0c;对应关系为&#xff1a;0-暂无评价&#xff0c;1-很差&#xff0c;2-差&#xff0c;3-一般&#xff0c;4-好&#xf…

计算机网络怎么查看连接打印机驱动,如何检测网络打印机是否已成功连接到计算机[检测方法]...

大概很多婴儿都像以前的编辑一样. 使用网络打印机时&#xff0c;有时它们可​​以打印打印机没有和电脑连接&#xff0c;有时却不能. 那么如何检测网络打印机是否已成功连接到计算机&#xff1f;跟随编辑器往下看.系统反复提示“无法打印”&#xff0c;因此本来很忙的小修几乎快…

eclipse python插件_pydev插件下载-eclipse中的python插件下载6.0.0 官网最新版-西西软件下载...

在eclipse中安装python所需的插件。PyDev for Eclipse 是一个功能强大且易用的 Eclipse Python IDE 插件。利用 PyDev 插件把 Eclipse 变为功能强大且易用的 Python IDE&#xff0c;如何利用其进行 Python 程序的开发和调试。安装方法&#xff1a;一种比较随意的方法就是把压缩…

a - 数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历_数据结构--图

故事凌 今天基本知识点图可说是所有数据结构里面知识点最丰富的一个, 自己笨的知识点如下:阶(oRDER), 度: 出度(out-Degree), 入度(in-Degree)树(Tree), 森林(Forest), 环(Loop)有向图(Directed Graph), 无向图(Undirected Graph), 完全有向图, 完全无向图连通图(Connected Gra…

vim: vimrc

2019独角兽企业重金招聘Python工程师标准>>> 打造vim CIDE http://blog.csdn.net/doc_sgl/article/details/47205779 转载于:https://my.oschina.net/u/2528742/blog/843176

计算机二级考试试题在线看,【TOP182015年全国计算机二级考试试题题库.doc文档免费在线阅读材料】...

TOP182015年全国计算机二级考试试题题库.doc文档免费在线阅读《2015年全国计算机二级考试试题题库.doc》由会员分享&#xff0c;可免费在线阅读全文&#xff0c;更多与《TOP182015年全国计算机二级考试试题题库.doc文档免费在线阅读》相关文档资源请在帮帮文库(www.woc88.com)数…

使用flask_socketio实现客户端间即时通信

关于flask_socketio的入门可以看我的上一篇博客《使用flask_socketio实现服务端向客户端定时推送》 用socketio实现即时通信十分简单&#xff0c;只需要客户端发送用户输入的信息到后端&#xff0c;后端再将此信息广播到所有连接到此命名域的客户端就可以了。 from flask impor…

java继承原理内存角度_Java基础知识巩固

最近发现自己的Java基础知识还是有点薄弱&#xff0c;刚好有点空闲时间进行再补一补&#xff0c;然后进行整理一下&#xff0c;方便自己以后复习。其实个人认为Java基础还是很重要的&#xff0c;不管从事Java后端开发还是Android开发&#xff0c;Java这块的基础还是重中之重&am…

python函数对变量的作用_python函数对变量的作用及遵循的原则

1.全局变量和局部变量全局变量&#xff1a;指在函数之外定义的变量&#xff0c;一般没有缩进&#xff0c;在程序执行的全过程有效局部变量&#xff1a;指在函数内部使用的变量&#xff0c;仅在函数内部有效&#xff0c;当函数退出时变量将不存在例如&#xff1a;1 n1 #n是全局变…

不用开发实现RDS RDWeb门户美化和个性化

个性化RDWeb界面RDWeb原生界面相对比较简洁&#xff0c;每个企业部署的RDWeb都是千篇一律的&#xff0c;有些用户可能希望将网页装饰得个性化点。在谈到自定义Web界面&#xff0c;第一反应可能是使用代码进行编写&#xff0c;但是这里要和大家分享的是无代码美化和自定义RDWeb界…

安卓使用富文本编辑器html5,Android富文本编辑器,图文详细

Android富文本编辑器,图文详细资源下载此资源下载价格为3D币&#xff0c;请先登录资源文件列表AndroidRichTextEditor/.classpath , 475AndroidRichTextEditor/.project , 857AndroidRichTextEditor/AndroidManifest.xml , 1281AndroidRichTextEditor/bin/AndroidManifest.xml …

python pip安装pyinstaller报错_pip install pyinstaller (安装过程报错解决)

安装目标&#xff1a;pip install pyinstaller报错内容&#xff1a;WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.You should consider upgrading via the python -m pip install --upgrade pip command.解决方法&#xff1a;运行--->c…

[SQL]LeetCode183. 从不订购的客户 | Customers Who Never Order

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号&#xff1a;山青咏芝&#xff08;shanqingyongzhi&#xff09;➤博客园地址&#xff1a;山青咏芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;➤GitHub地址&a…

access四舍五入取整round_access中round函数怎么用

access中round函数怎么用?access中round函数的用法&#xff01;下面&#xff0c;小编通过示例来给大家介绍access中round函数的用法。工具/原料access 2007方法/步骤打开access应用程序&#xff0c;新建一个数据库&#xff0c;并新建如下图所示的worker数据表&#xff0c;用于…

其他大神的配置 nginx 配置参考

2019独角兽企业重金招聘Python工程师标准>>> user nginx nginx; worker_processes 2; #error_log logs/error.log; error_log logs/error.log notice; #error_log logs/error.log info; pid logs/nginx.pid; google_perftools_profiles /tmp/tcmalloc; worker_rlim…

小孩用计算机做作业怎么表达,计算机作业

满意答案尧Dreaman夕2014.09.25采纳率&#xff1a;40% 等级&#xff1a;10已帮助&#xff1a;1121人Windows中可以设置、控制计算机硬件配置和修改桌面布局的应用程序是( D)A) Word B) Excel C)资源管理器 D)控制面板多窗口的切换可以通过(D )来实现A)在任务栏上用鼠标单击右…

Delphi读写二进制文件

http://www.cnblogs.com/hnxxcxg/p/3691742.html 二进制文件&#xff08;也叫类型文件&#xff09;&#xff0c;二进制文件是由一批同一类型的数据组成的一个数据序列&#xff0c;就是说一个具体的二进制文件只能存放同一种类型的数据。type TMember record Name : string[10]…

[No0000178]改善C#程序的建议1:非用ICloneable不可的理由

好吧&#xff0c;我承认&#xff0c;这是一个反标题&#xff0c;实际的情况是&#xff1a;我找不到一个非用ICloneable不可的理由。事实上&#xff0c;接口ICloneable还会带来误解&#xff0c;因为它只有一个Clone方法。 我们都知道&#xff0c;对象的拷贝分为&#xff1a;浅拷…

uniapp网络请求获取数据_2.uni-app 发起网络请求

## uni.request(OBJECT)发起网络请求。**OBJECT 参数说明**![](https://box.kancloud.cn/a90bf284df069eddde4019c04db7d627_861x475.png)**success 返回参数说明**![](https://box.kancloud.cn/10d44a6d100bb3833b22f2d41e85d8eb_861x165.png)**data 数据说明**最终发送给服务…

SOM 的两种算法

我参考了这篇文章http://www.scholarpedia.org/article/Kohonen_network另一个很好的演示在这里http://www.math.le.ac.uk/people/ag153/homepage/PCA_SOM/PCA_SOM.htmlSOMt是训练步一个输入数据是n维向量待训练的是一堆节点&#xff0c;这堆节点之间有边连着&#xff0c;通常是…