欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中Dapper的使用教程

程序员文章站 2022-03-24 09:53:18
一、什么是dapper  dapper是一款轻量级orm工具(github)。如果你在小的项目中,使用entity framework、nhibernate 来处理大数据访问及关系映射,未免有点杀鸡用...

一、什么是dapper

  dapper是一款轻量级orm工具(github)。如果你在小的项目中,使用entity framework、nhibernate 来处理大数据访问及关系映射,未免有点杀鸡用牛刀。你又觉得orm省时省力,这时dapper 将是你不二的选择。

二、dapper的优点

  1. 轻量。只有一个文件sqlmapper.cs,编译后就40k的一个很小的dll.
  2. 速度快。dapper的速度接近与idatareader,取列表的数据超过了datatable。
  3. 支持多种数据库。dapper可以在所有ado.net providers下工作,包括sqlite, sqlce, firebird, oracle, mysql, postgresql and sql server
  4. 可以映射一对一,一对多,多对多等多种关系。
  5. 性能高。通过emit反射idatareader的序列队列,来快速的得到和产生对象,性能不错。
  6. 支持framework2.0,3.0,3.5,4.0,4.5
  7. dapper语法十分简单。并且无须迁就数据库的设计。

三、使用方法

  1、添加nuget程序包dapper

  C#中Dapper的使用教程

  2、配置文件添加连接数据库的字符串

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedruntime version="v4.0" sku=".netframework,version=v4.8"/>
  </startup>
  <connectionstrings>
    <add name="mystrconn" connectionstring="data source=(localdb)\mssqllocaldb;initial catalog=dhr_db;integrated security=true" />
  </connectionstrings>
</configuration>

  3、添加dappertools.cs(添加、批量添加、删除、批量删除、修改、批量修改、查询、查询in的操作、多语句操作)

// <copyright file="dappertools.cs" company="placeholdercompany">
// copyright (c) placeholdercompany. all rights reserved.
// </copyright>

namespace csharpstudy
{
    using system;
    using system.collections.generic;
    using system.configuration;
    using system.data;
    using system.data.sqlclient;
    using system.linq;
    using system.text;
    using system.threading.tasks;
    using dapper;

    internal class dappertools
    {
        public static string connectionstring = configurationmanager.connectionstrings["mystrconn"].connectionstring;

        /// <summary>
        /// 添加.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入实体类型.</param>
        /// <returns>int.</returns>
        public static int add<t>(string sql, t t)
            where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.execute(sql, t);
            }
        }

        /// <summary>
        /// 批量添加.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入泛型类.</param>
        /// <returns>int.</returns>
        public static int add<t>(string sql, list<t> t)
            where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.execute(sql, t);
            }
        }

        /// <summary>
        /// 删除.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入实体类型.</param>
        /// <returns>int.</returns>
        public static int delete<t>(string sql, t t)
              where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.execute(sql, t);
            }
        }

        /// <summary>
        /// 批量删除.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入泛型类.</param>
        /// <returns>int.</returns>
        public static int delete<t>(string sql, list<t> t)
              where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.execute(sql, t);
            }
        }

        /// <summary>
        /// 修改.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入实体类型.</param>
        /// <returns>int.</returns>
        public static int update<t>(string sql, t t)
              where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.execute(sql, t);
            }
        }

        /// <summary>
        /// 批量修改.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入泛型类.</param>
        /// <returns>int.</returns>
        public static int update<t>(string sql, list<t> t)
              where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.execute(sql, t);
            }
        }

        /// <summary>
        /// 查询.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <returns>泛型类.</returns>
        public static list<t> query<t>(string sql)
             where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.query<t>(sql).tolist();
            }
        }

        /// <summary>
        /// 查询指定数据.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <param name="t">传入泛型类.</param>
        /// <returns>类.</returns>
        public static t query<t>(string sql, t t)
             where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.query<t>(sql, t).singleordefault();
            }
        }

        /// <summary>
        /// 查询的in操作.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        /// <returns>泛型类.</returns>
        public static list<t> query<t>(string sql, int[] ids)
            where t : class
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                return connection.query<t>(sql, new { ids }).tolist();
            }
        }

        /// <summary>
        /// 多语句操作.
        /// </summary>
        /// <typeparam name="t">实体类型.</typeparam>
        /// <param name="sql">传入sql执行语句.</param>
        public static void querymultiple(string sql)
        {
            using (idbconnection connection = new sqlconnection(connectionstring))
            {
                var multireader = connection.querymultiple(sql);
                var userinfo = multireader.read<userinfo>();
                var student = multireader.read<student>();

                multireader.dispose();
            }
        }
    }
}

  4、添加测试类student.cs、userinfo。表数据自己添加

 public class student
    {
        public int id { get; set; }

        public string name { get; set; }

        public int age { get; set; }

        public string memo { get; set; }

        public datetime createtime { get; set; }

        public datetime updatetime { get; set; }
    }
public class userinfo
    {
        public int id { get; set; }

        public string name { get; set; }

        public int age { get; set; }

        public string memo { get; set; }

        public datetime createtime { get; set; }

        public datetime updatetime { get; set; }
    }

  5、调用方法

//-----------------------------------------------------------------------
// <copyright file="program.cs" company="placeholdercompany">
// copyright (c) placeholdercompany. all rights reserved.
// </copyright>
// <author>john doe</author>
//-----------------------------------------------------------------------

namespace csharpstudy
{
    using system;
    using system.collections.generic;
    using system.linq;
    using system.text;
    using system.threading.tasks;
    using dapper;

    internal class program
    {
        private static void main(string[] args)
        {
            // --------------添加--------------
            // userinfo user = new userinfo();
            // user.name = "九九";
            // user.age = 10;
            // user.memo = "这是备注";
            // user.createtime = datetime.now;

            // string sql = "insert into userinfo(name,age,memo,createtime) values (@name, @age, @memo,@createtime)";
            // int result = dappertools.add<userinfo>(sql, user);
            // if (result > 0)
            // {
            //     console.writeline("添加成功");
            //     console.readkey();
            // }

            // --------------批量添加--------------
            // userinfo user = new userinfo();
            // user.name = "李奎";
            // user.age = 50;
            // user.memo = "这是备注";
            // user.createtime = datetime.now;

            // userinfo user2 = new userinfo();
            // user2.name = "梁山伯";
            // user2.age = 54;
            // user2.memo = "这是备注";
            // user2.createtime = datetime.now;

            // list<userinfo> list = new list<userinfo>();
            // list.add(user);
            // list.add(user2);

            // string sql = "insert into userinfo(name,age,memo,createtime) values (@name, @age, @memo,@createtime)";
            // int result = dappertools.add<userinfo>(sql, list);
            // if (result > 0)
            // {
            //     console.writeline("添加成功");
            //     console.readkey();
            // }

            // --------------删除--------------
            // userinfo user = new userinfo();
            // user.id = 18;

            // string sql = "delete from userinfo where id=@id";
            // int result = dappertools.delete<userinfo>(sql, user);
            // if (result > 0)
            // {
            //     console.writeline("删除成功");
            //     console.readkey();
            // }

            // --------------批量删除--------------
            // userinfo user = new userinfo();
            // user.id = 15;

            // userinfo user2 = new userinfo();
            // user2.id = 16;

            // list<userinfo> list = new list<userinfo>();
            // list.add(user);
            // list.add(user2);

            // string sql = "delete from userinfo where id=@id";
            // int result = dappertools.delete<userinfo>(sql, list);
            // if (result > 0)
            // {
            //     console.writeline("添加成功");
            //     console.readkey();
            // }

            // --------------修改--------------
            // userinfo user = new userinfo();
            // user.id = 14;
            // user.name = "九九";

            // string sql = "update userinfo set name=@name,updatetime=getdate() where id=@id";
            // int result = dappertools.update<userinfo>(sql, user);
            // if (result > 0)
            // {
            //     console.writeline("修改成功");
            //     console.readkey();
            // }

            // --------------批量修改--------------
            // userinfo user = new userinfo();
            // user.id = 13;
            // user.name = "王文";

            // userinfo user2 = new userinfo();
            // user2.id = 14;
            // user2.name = "冰冰";

            // list<userinfo> list = new list<userinfo>();
            // list.add(user);
            // list.add(user2);

            // string sql = "update userinfo set name=@name,updatetime=getdate() where id=@id";
            // int result = dappertools.update<userinfo>(sql, list);
            // if (result > 0)
            // {
            //     console.writeline("修改成功");
            //     console.readkey();
            // }

            // --------------查询--------------
            // string sql = "select * from userinfo";
            // list<userinfo> list = dappertools.query<userinfo>(sql);
            // foreach (var item in list)
            // {
            //     console.writeline(item.id + "-" + item.name + "-" + item.age + "-" + item.memo);
            // }

            // console.readkey();

            // --------------查询指定数据--------------
            // userinfo user = new userinfo();
            // user.id = 14;

            // string sql = "select * from userinfo where id=@id";
            // userinfo userinfo = dappertools.query<userinfo>(sql, user);

            // console.writeline(userinfo.id + "-" + userinfo.name + "-" + userinfo.age + "-" + userinfo.memo);
            // console.readkey();

            // --------------查询的in操作--------------
            // string sql = "select * from userinfo where id in @ids";
            // int[] ids = { 1, 2 };

            // list<userinfo> list = dappertools.query<userinfo>(sql, ids);
            // foreach (var item in list)
            // {
            //     console.writeline(item.id + "-" + item.name + "-" + item.age + "-" + item.memo);
            // }

            // --------------多语句操作--------------
            // string sql = "select * from userinfo;select * from student";

            // dappertools.querymultiple(sql);
        }
    }
}

源代码:

链接: https://pan.baidu.com/s/1im3dicqjcospvr11h6zddq

提取码: 6ag9

后续会陆续更新其他资料,喜欢请关注哦!

我的博客:

到此这篇关于c# dapper的使用的文章就介绍到这了,更多相关c#使用dapper内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: C# Dapper