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

C# ORM学习笔记:Dapper基本用法

程序员文章站 2022-05-18 19:22:03
一、基础知识 1.1、Dapper简介 Dapper是.NET下的一个micro ORM,它和Entity Framework或NHibnate不同,属于轻量级并且是半自动的(实体类都要自己写)。假如你喜欢原生的Sql语句,又喜欢ORM的简单,那你一定会喜欢上Dapper这款ORM。 1.2、Dap ......

    一、基础知识

    1.1、dapper简介

    dapper是.net下的一个micro orm,它和entity framework或nhibnate不同,属于轻量级并且是半自动的(实体类都要自己写)。假如你喜欢原生的sql语句,又喜欢orm的简单,那你一定会喜欢上dapper这款orm。

    1.2、dapper优点

    1)轻量。只有一个文件(sqlmapper.cs)。

    2)速度快。dapper的速度接近于idatareader,取列表的数据超过了datatable。

    3)支持多种数据库。包括sqlite、sqlce、firebird、oracle、mysql、postgresql、sql server。

    4)可以映射一对一、一对多、多对多等多种关系。

    5)性能高。通过emit反射idatareader的序列队列,来快速地得到和产生对象。

    1.3、dapper安装

    此处使用dapper扩展库dapper.simplecrud,它也会默认安装dapper(依赖项):

    项目右键->管理 nuget 程序包->dapper.simplecrud。

C# ORM学习笔记:Dapper基本用法

    二、数据准备

    2.1、数据表

    在sql server中创建4个数据表,分别是:student(学生表)、teacher(教师表)、course(课程表)、record(成绩表)。

--学生表
create table [dbo].[student](
    [studentid] [int] identity(1,1) not null,
    [name] [nvarchar](50) null,
    [age] [smallint] null,
    [gender] [nvarchar](10) null,
 constraint [pk_student] primary key clustered 
(
    [studentid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]

--教师表
create table [dbo].[teacher](
    [teacherid] [int] identity(1,1) not null,
    [name] [nvarchar](50) null,
 constraint [pk_teacher] primary key clustered 
(
    [teacherid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]

--课程表
create table [dbo].[course](
    [courseid] [int] identity(1,1) not null,
    [name] [nvarchar](50) null,
    [teacherid] [int] null,
 constraint [pk_course] primary key clustered 
(
    [courseid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]

--成绩表
create table [dbo].[record](
    [studentid] [int] not null,
    [courseid] [int] not null,
    [score] [numeric](8, 2) null,
 constraint [pk_score] primary key clustered 
(
    [studentid] asc,
    [courseid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]

--学生表数据插入
insert into student (name,age,gender)
select n'刘一',18,n'female'
union
select n'陈二',19,n'female'
union
select n'张三',18,n'male'
union
select n'李四',19,n'male'
union
select n'王五',18,n'male'
union
select n'赵六',19,n'male'
union
select n'孙七',19,n'female'

--教师表数据插入
insert into teacher (name)
select n'周八'
union
select n'吴九'
union
select n'郑十'

--课程表数据插入
insert into course (name,teacherid)
select n'离散数学',1
union
select n'程序设计',2
union
select n'数据结构',3

--成绩表数据插入
insert into record (studentid,courseid,score )
select 1,1,90
union
select 2,1,91
union
select 3,1,89
union
select 4,1,75
union
select 5,1,96
union
select 6,1,78
union
select 7,1,83
union
select 1,2,86
union
select 2,2,92
union
select 3,2,77
union
select 4,2,71
union
select 5,2,66
union
select 6,2,87
union
select 7,2,93
union
select 1,3,81
union
select 2,3,90
union
select 3,3,88
union
select 4,3,82
union
select 5,3,93
union
select 6,3,91
union
select 7,3,84

    2.2、实体类

    dapper的实体映射:

    1)属性不编辑,用[editable(false)]这个特性标记,默认是true。

    2)类名到表名的映射,用[table("tablename")]特性,tablename对应物理数据表名称。

    3)主键映射,如果您的实体类中有id属性,dapper会默认此属性为主键,否则要为作为主键的属性添加[key]特性。

    由上可知,如student表,其实体类应该生成下面这个样子:

using system;
using system.collections.generic;
using system.text;
using dapper;

namespace linkto.test.consoledapper
{
    [table("student")]
    [serializable]
    public class student
    {
        [key]
        public int? studentid {get; set;}

        public string name {get; set;}

        public short? age {get; set;}

        public string gender {get; set;}
    }
}

    2.3、使用t4模板生成实体类

    2.3.1、t4code文件夹的文本模板

<#@ assembly name="system.core" #>
<#@ assembly name="system.data" #>
<#@ import namespace="system.linq" #>
<#@ import namespace="system.text" #>
<#@ import namespace="system.collections.generic" #>
<#@ import namespace="system.data"#>
<#@ import namespace="system.data.sqlclient"#>
<#+
    #region t4code
    /// <summary>
    /// 数据库架构接口
    /// </summary>
    public interface idbschema : idisposable
    {
        list<string> gettablelist();
        datatable gettablemetadata(string tablename);
    }

    /// <summary>
    /// 数据库架构工厂
    /// </summary>
    public class dbschemafactory
    {
        static readonly string databasetype = "sqlserver";
        public static idbschema getdbschema()
        {
            idbschema dbschema;
            switch (databasetype) 
            {
                case "sqlserver":
                    {
                        dbschema =new sqlserverschema();
                        break;
                    }
                default: 
                    {
                        throw new argumentexception("the input argument of databasetype is invalid.");
                    }
            }
            return dbschema;
        }
    }

    /// <summary>
    /// sqlserver
    /// </summary>
    public class sqlserverschema : idbschema
    {
        public string connectionstring = "server=.;database=test;uid=sa;pwd=********;";
        public sqlconnection conn;

        public sqlserverschema()
        {
            conn = new sqlconnection(connectionstring);
            conn.open();
        }

        public list<string> gettablelist()
        {
            list<string> list = new list<string>();
            string commandtext = "select name table_name from sysobjects where xtype='u' order by name";

            using(sqlcommand cmd = new sqlcommand(commandtext, conn))
            {
                using (sqldatareader dr = cmd.executereader(commandbehavior.closeconnection))
                {
                    while (dr.read())
                    {
                        list.add(dr["table_name"].tostring());
                    }
                }
            }

            return list;
        }
        
        public datatable gettablemetadata(string tablename)
        {
            string commandtext=string.format
                (
                    "select a.name table_name,b.name field_name,c.name datatype,isnull(b.prec,0) length, "+
                        "convert(bit,case when not f.id is null then 1 else 0 end) iskey, "+
                        "convert(bit,case when columnproperty(b.id,b.name,'isidentity') = 1 then 1 else 0 end) as isidentity, "+
                        "convert(bit,b.isnullable) isnullable "+
                    "from sysobjects a inner join syscolumns b on a.id=b.id inner join systypes c on b.xtype=c.xusertype "+
                        "left join sysobjects d on b.id=d.parent_obj and d.xtype='pk' "+
                        "left join sysindexes e on b.id=e.id and d.name=e.name "+
                        "left join sysindexkeys f on b.id=f.id and b.colid=f.colid and e.indid=f.indid "+
                    "where a.xtype='u' and a.name='{0}' "+
                    "order by a.name,b.colorder", tablename
                );

            using(sqlcommand cmd = new sqlcommand(commandtext, conn))
            {
                sqldataadapter da = new sqldataadapter(cmd);
                dataset ds = new dataset();
                da.fill(ds,"schema");
                return ds.tables[0];
            }
        }

        public void dispose()
        {
            if (conn != null)
            {
                conn.close();
            }
        }
    }
    #endregion
#>
<#@ assembly name="system.core" #>
<#@ assembly name="system.data" #>
<#@ assembly name="envdte" #>
<#@ import namespace="system.linq" #>
<#@ import namespace="system.text" #>
<#@ import namespace="system.collections.generic" #>
<#@ import namespace="system.data"#>
<#@ import namespace="system.io"#>
<#@ import namespace="microsoft.visualstudio.texttemplating"#>

<#+
// t4 template block manager for handling multiple file outputs more easily.
// copyright (c) microsoft corporation.all rights reserved.
// this source code is made available under the terms of the microsoft public license (ms-pl)

// manager class records the various blocks so it can split them up
class manager
{
    public struct block
    {
        public string name;
        public int start, length;
    }

    public list<block> blocks = new list<block>();
    public block currentblock;
    public block footerblock = new block();
    public block headerblock = new block();
    public itexttemplatingenginehost host;
    public managementstrategy strategy;
    public stringbuilder template;
    public string outputpath { get; set; }

    public manager(itexttemplatingenginehost host, stringbuilder template, bool commonheader)
    {
        this.host = host;
        this.template = template;
        outputpath = string.empty;
        strategy = managementstrategy.create(host);
    }

    public void startblock(string name)
    {
        currentblock = new block { name = name, start = template.length };
    }

    public void startfooter()
    {
        footerblock.start = template.length;
    }

    public void endfooter()
    {
        footerblock.length = template.length - footerblock.start;
    }

    public void startheader()
    {
        headerblock.start = template.length;
    }

    public void endheader()
    {
        headerblock.length = template.length - headerblock.start;
    }    

    public void endblock()
    {
        currentblock.length = template.length - currentblock.start;
        blocks.add(currentblock);
    }

    public void process(bool split)
    {
        string header = template.tostring(headerblock.start, headerblock.length);
        string footer = template.tostring(footerblock.start, footerblock.length);
        blocks.reverse();
        foreach(block block in blocks) {
            string filename = path.combine(outputpath, block.name);
            if (split) {
                string content = header + template.tostring(block.start, block.length) + footer;
                strategy.createfile(filename, content);
                template.remove(block.start, block.length);
            } else {
                strategy.deletefile(filename);
            }
        }
    }
}

class managementstrategy
{
    internal static managementstrategy create(itexttemplatingenginehost host)
    {
        return (host is iserviceprovider) ? new vsmanagementstrategy(host) : new managementstrategy(host);
    }

    internal managementstrategy(itexttemplatingenginehost host) { }

    internal virtual void createfile(string filename, string content)
    {
        file.writealltext(filename, content);
    }

    internal virtual void deletefile(string filename)
    {
        if (file.exists(filename))
            file.delete(filename);
    }
}

class vsmanagementstrategy : managementstrategy
{
    private envdte.projectitem templateprojectitem;

    internal vsmanagementstrategy(itexttemplatingenginehost host) : base(host)
    {
        iserviceprovider hostserviceprovider = (iserviceprovider)host;
        if (hostserviceprovider == null)
            throw new argumentnullexception("could not obtain hostserviceprovider");

        envdte.dte dte = (envdte.dte)hostserviceprovider.getservice(typeof(envdte.dte));
        if (dte == null)
            throw new argumentnullexception("could not obtain dte from host");

        templateprojectitem = dte.solution.findprojectitem(host.templatefile);
    }

    internal override void createfile(string filename, string content)
    {
        base.createfile(filename, content);
        ((eventhandler)delegate { templateprojectitem.projectitems.addfromfile(filename); }).begininvoke(null, null, null, null);
    }

    internal override void deletefile(string filename)
    {
        ((eventhandler)delegate { findanddeletefile(filename); }).begininvoke(null, null, null, null);
    }

    private void findanddeletefile(string filename)
    {
        foreach(envdte.projectitem projectitem in templateprojectitem.projectitems)
        {
            if (projectitem.get_filenames(0) == filename)
            {
                projectitem.delete();
                return;
            }
        }
    }
}
#>

    dbschema.ttinclude主要实现了数据库工厂的功能。注:请将数据库连接字符串改成您自己的。

    multidocument.ttinclude主要实现了多文档的功能。

    2.3.2、生成实体类的文本模板

<#@ template debug="true" hostspecific="true" language="c#" #>
<#@ assembly name="system.core" #>
<#@ import namespace="system.linq" #>
<#@ import namespace="system.text" #>
<#@ import namespace="system.collections.generic" #>
<#@ output extension=".cs" #>
<#@ include file="t4code/dbschema.ttinclude"#>
<#@ include file="t4code/multidocument.ttinclude"#>
<# var manager = new manager(host, generationenvironment, true) { outputpath = path.getdirectoryname(host.templatefile)}; #>
<#
    //system.diagnostics.debugger.launch();//调试
    var dbschema = dbschemafactory.getdbschema();
    list<string> tablelist = dbschema.gettablelist();
    foreach (string tablename in tablelist)
    {
        manager.startblock(tablename+".cs");
        datatable table = dbschema.gettablemetadata(tablename);

        //获取主键
        string strkey = string.empty;
        foreach (datarow datarow in table.rows)
        {
            if ((bool)datarow["iskey"] == true)
            {
                strkey = datarow["field_name"].tostring();
                break;
            }
        }
        
#>
//-------------------------------------------------------------------------------
// 此代码由t4模板multimodelauto自动生成
// 生成时间 <#= datetime.now.tostring("yyyy-mm-dd hh:mm:ss") #>
// 对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
//-------------------------------------------------------------------------------

using system;
using system.collections.generic;
using system.text;
using dapper;

namespace linkto.test.consoledapper
{
    [table("<#= tablename #>")]
    [serializable]
    public class <#= tablename #>
    {
<#
        foreach (datarow datarow in table.rows)
        {
            //获取数据类型
            string dbdatatype = datarow["datatype"].tostring();
            string datatype = string.empty;
                    
            switch (dbdatatype)
            {
                case "decimal":
                case "numeric":
                case "money":
                case "smallmoney":
                    datatype = "decimal?";
                    break;
                case "char":
                case "nchar":
                case "varchar":
                case "nvarchar":
                case "text":
                case "ntext":
                    datatype = "string";
                    break;
                case "uniqueidentifier":
                    datatype = "guid?";
                    break;
                case "bit":
                    datatype = "bool?";
                    break;
                case "real":
                    datatype = "single?";
                    break;
                case "bigint":
                    datatype = "long?";
                    break;
                case "int":
                    datatype = "int?";
                    break;
                case "tinyint":
                case "smallint":
                    datatype = "short?";
                    break;
                case "float":
                    datatype = "float?";
                    break;
                case "date":
                case "datetime":
                case "datetime2":
                case "smalldatetime":
                    datatype = "datetime?";
                    break;
                case "datetimeoffset ":
                    datatype = "datetimeoffset?";
                    break;
                case "timespan ":
                    datatype = "timespan?";
                    break;
                case "image":
                case "binary":
                case "varbinary":
                    datatype = "byte[]";
                    break;
                default:
                    break;
            }
            if (datarow["field_name"].tostring() == strkey)
            {
#>
        [key]
        public <#= datatype #> <#= datarow["field_name"].tostring() #> {get; set;}
<#
            }
            else
            {
#>

        public <#= datatype #> <#= datarow["field_name"].tostring() #> {get; set;}
<# 
            }
        }
#>
    }
}
<#
        manager.endblock();
    }
    dbschema.dispose();
    manager.process(true);
#>

    三、crud

    3.1、connectionstrings

    在app.config中添加数据库连接字符串:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup> 
    <supportedruntime version="v4.0" sku=".netframework,version=v4.6.1" />
  </startup>
  <connectionstrings>
    <add name="connstring" connectionstring="server=.;database=test;uid=sa;pwd=********;" />
  </connectionstrings>
</configuration>

    添加一个dapperhelper类,实现数据库连接及后续的crud。

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;

namespace linkto.test.consoledapper
{
    public class dapperhelper
    {
        public static idbconnection connection = null;

        public dapperhelper()
        { }

        private idbconnection getcon()
        {
            if (connection == null)
            {
                connection = new sqlconnection(configurationmanager.connectionstrings["connstring"].connectionstring);
            }
            return connection;
        }
    }
}

    3.2、create

    a1)通过sql插入单条数据(带参数),返回结果是影响行数。

        /// <summary>
        /// 通过sql插入单条数据(带参数),返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? insertwithsqla()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "insert into student (name,age,gender) values (@name,@age,@gender)";
                return conn.execute(strsql, new { name = "hello", age = 18, gender = "male" });
            }
        }

    a2)通过sql插入单条数据(带实体),返回结果是影响行数。

        /// <summary>
        /// 通过sql插入单条数据(带实体),返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? insertwithsqlb()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "insert into student (name,age,gender) values (@name,@age,@gender)";
                student student = new student
                {
                    name = "hello",
                    age = 18,
                    gender = "male"
                };
                return conn.execute(strsql, student);
            }
        }

    a3)通过sql插入单条数据(带实体),返回主键值。

        /// <summary>
        /// 通过sql插入单条数据(带实体),返回主键值。
        /// </summary>
        /// <returns></returns>
        public int? insertwithsqlc()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "insert into student (name,age,gender) values (@name,@age,@gender)";
                student student = new student
                {
                    name = "hello",
                    age = 18,
                    gender = "male"
                };
                strsql += " select scope_identity()";
                return conn.queryfirstordefault<int>(strsql, student);
            }
        }

    a4)通过sql插入多条数据(带实体),返回结果是影响行数。

        /// <summary>
        /// 通过sql插入多条数据(带实体),返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? insertwithsqld()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "insert into student (name,age,gender) values (@name,@age,@gender)";
                list<student> list = new list<student>();
                for (int i = 0; i < 3; i++)
                {
                    student student = new student
                    {
                        name = "world" + i.tostring(),
                        age = 18,
                        gender = "male"
                    };
                    list.add(student);
                }
                return conn.execute(strsql, list);
            }
        }

    b)通过实体插入数据,返回结果是主键值。

        /// <summary>
        /// 通过实体插入数据,返回结果是主键值。
        /// </summary>
        /// <returns></returns>
        public int? insertwithentity()
        {
            using (var conn = getcon())
            {
                conn.open();
                var entity = new student { name = "world", age = 18, gender = "male" };
                return conn.insert(entity);
            }
        }

    3.3、read

    a1)通过sql查询数据(查询所有数据)

        /// <summary>
        /// 通过sql查询数据(查询所有数据)
        /// </summary>
        /// <returns></returns>
        public ienumerable<student> getstudentlist1()
        {
            string strsql = "select * from student";
            using (var conn = getcon())
            {
                conn.open();
                return conn.query<student>(strsql);
            }
        }

    a2)通过sql查询数据(带参数)

        /// <summary>
        /// 通过sql查询数据(带参数)
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        public student getstudentlist1a(int studentid)
        {
            string strsql = "select * from student where studentid=@studentid";
            using (var conn = getcon())
            {
                conn.open();
                return conn.query<student>(strsql, new { studentid = studentid }).firstordefault();
            }
        }

    a3)通过sql查询数据(in)

        /// <summary>
        /// 通过sql查询数据(in)
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        public ienumerable<student> getstudentlist1b(string studentid)
        {
            string strsql = "select * from student where studentid in @studentid";
            var idarr = studentid.split(',');
            using (var conn = getcon())
            {
                conn.open();
                return conn.query<student>(strsql, new { studentid = idarr });
            }
        }

    b1)通过实体查询数据(查询所有数据)

        /// <summary>
        /// 通过实体询数据(查询所有数据)
        /// </summary>
        /// <returns></returns>
        public ienumerable<student> getstudentlist2()
        {
            using (var conn = getcon())
            {
                conn.open();
                return conn.getlist<student>();
            }
        }

    b2)通过实体查询数据(指定id)

        /// <summary>
        /// 通过实体询数据(指定id)
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        public student getstudentlist2a(int studentid)
        {
            using (var conn = getcon())
            {
                conn.open();
                return conn.get<student>(studentid);
            }
        }

    b3)通过实体查询数据(带参数)

        /// <summary>
        /// 通过实体询数据(带参数)
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        public student getstudentlist2b(int studentid)
        {
            using (var conn = getcon())
            {
                conn.open();
                return conn.getlist<student>(new { studentid = studentid }).firstordefault();
            }
        }

    c1)多表查询(querymultiple),主要操作:通过querymultiple方法,返回查询中每条sql语句的数据集合。

        /// <summary>
        /// 多表查询(querymultiple)
        /// </summary>
        /// <returns></returns>
        public string getmultientitya()
        {
            string strsql = "select * from student as a;select * from teacher as a";
            stringbuilder sbstudent = new stringbuilder();
            stringbuilder sbteacher = new stringbuilder();
            using (var conn = getcon())
            {
                conn.open();
                var grid = conn.querymultiple(strsql);
                var students = grid.read<student>();
                var teachers = grid.read<teacher>();
                foreach (var item in students)
                {
                    sbstudent.append($"studentid={item.studentid} name={item.name} age={item.age} gender={item.gender}\n");
                }
                foreach (var item in teachers)
                {
                    sbteacher.append($"teacherid={item.teacherid} name={item.name}\n");
                }
                return sbstudent.tostring() + sbteacher.tostring();
            }
        }

    c2)多表查询(query),主要操作:通过sql进行多表关联查询,返回查询结果的数据集合。

        /// <summary>
        /// 多表查询(query)
        /// </summary>
        /// <returns></returns>
        public string getmultientityb()
        {
            string strsql = "select a.name coursename,b.name teachername from course a inner join teacher b on a.teacherid=b.teacherid";
            stringbuilder sbresult = new stringbuilder();
            using (var conn = getcon())
            {
                conn.open();
                var query = conn.query(strsql);
                query.aslist().foreach(q =>
                {
                    sbresult.append($"coursename={q.coursename} teachername={q.teachername}\n");
                });
                return sbresult.tostring();
            }
        }

    3.4、update

    a1)通过sql更新数据(带参数),返回结果是影响行数。

        /// <summary>
        /// 通过sql更新数据(带参数),返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? updatewithsqla()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "update student set name=@name,age=@age,gender=@gender where studentid=@studentid";
                return conn.execute(strsql, new { name = "world3", age = 19, gender = "female", studentid = 17 });
            }
        }

    a2)通过sql插入单条数据(带实体),返回结果是影响行数。

        /// <summary>
        /// 通过sql更新数据(带实体),返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? updatewithsqlb()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "update student set name=@name,age=@age,gender=@gender where studentid=@studentid";
                student student = new student
                {
                    studentid = 17,
                    name = "world3",
                    age = 18,
                    gender = "male"
                };
                return conn.execute(strsql, student);
            }
        }

    b)通过实体更新数据,返回结果是影响行数。

        /// <summary>
        /// 通过实体更新数据,返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? updatewithentity()
        {
            using (var conn = getcon())
            {
                conn.open();
                var entity = new student { studentid = 17, name = "world4", age = 18, gender = "male" };
                return conn.update(entity);
            }
        }

    3.5、delete

    a)通过sql删除数据(带参数),返回结果是影响行数。

        /// <summary>
        /// 通过sql删除数据(带参数),返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? deletewithsql()
        {
            using (var conn = getcon())
            {
                conn.open();
                string strsql = "delete from student where studentid=@studentid";
                return conn.execute(strsql, new { studentid = 16 });
            }
        }

    b)通过实体删除数据,返回结果是影响行数。

        /// <summary>
        /// 通过实体删除数据,返回结果是影响行数。
        /// </summary>
        /// <returns></returns>
        public int? deletewithentity()
        {
            using (var conn = getcon())
            {
                conn.open();
                var entity = new student { studentid = 17 };
                return conn.delete(entity);
            }
        }

    四、procedure

    4.1、带输出参数的存储过程

create procedure [dbo].[getstudentage]
    @studentid int,
    @name nvarchar(50) output
as
begin
    declare @age smallint
    select @name=name,@age=age from student where studentid=@studentid
    select @age
end
        /// <summary>
        /// 带输出参数的存储过程
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        public tuple<string, int> getstudentage(int studentid)
        {
            int age = 0;
            var para = new dynamicparameters();
            para.add("studentid", 1);
            para.add("name", string.empty, dbtype.string, parameterdirection.output);

            using (var conn = getcon())
            {
                conn.open();
                age = conn.query<int>("getstudentage", para, commandtype: commandtype.storedprocedure).firstordefault();
            }

            return tuple.create(para.get<string>("name"), age);
        }
  

   五、transaction

    5.1、在idbconnection下事务,主要操作:在执行insert方法时传入transaction;在正常情况下commit事务;在异常时回滚事务。

        /// <summary>
        /// 在idbconnection下事务
        /// </summary>
        /// <returns></returns>
        public bool insertwithtran()
        {
            using (var conn = getcon())
            {
                conn.open();
                int studentid = 0, teacherid = 0, result = 0;
                var student = new student { name = "sandy", age = 18, gender = "female" };
                var teacher = new teacher { name = "luci" };
                var tran = conn.begintransaction();
                try
                {
                    studentid = conn.insert(student, tran).value;
                    result++;
                    teacherid = conn.insert(teacher, tran).value;
                    result++;
                    tran.commit();
                }
                catch
                {
                    result = 0;
                    tran.rollback();
                }
                return result > 0;
            }
        }

    5.2、在存储过程下事务,主要操作:在存储过程中进行事务;通过dynamicparameters传递参数给存储过程;通过query调用存储过程。

create procedure [dbo].[insertdata]
    --student
    @studentname nvarchar(50),
    @age smallint,
    @gender nvarchar(10),
    --teacher
    @teachername nvarchar(50)
as
begin
    --变量定义
    declare @result bit=1    --结果标识
    
    --事务开始
    begin transaction

    --数据插入
    insert into student (name,age,gender) values (@studentname,@age,@gender)
    insert into teacher (name) values (@teachername)
    
    --事务执行
    if @@error=0
    begin
        commit transaction
    end
    else
    begin
        set @result=0
        rollback transaction
    end

    --结果返回
    select @result
end
        /// <summary>
        /// 在存储过程下事务
        /// </summary>
        /// <returns></returns>
        public bool insertwithproctran()
        {
            var para = new dynamicparameters();
            para.add("studentname", "hanmeimei");
            para.add("age", 18);
            para.add("gender", "female");
            para.add("teachername", "angel");

            using (var conn = getcon())
            {
                conn.open();
                return conn.query<bool>("insertdata", para, commandtype: commandtype.storedprocedure).firstordefault();
            }
        }

    六、paging

    6.1、简单分页

        /// <summary>
        /// 简单分页
        /// </summary>
        /// <param name="beginrownum"></param>
        /// <param name="endrownum"></param>
        /// <returns></returns>
        public ienumerable<student> getpaging(int beginrownum = 1, int endrownum = 5)
        {
            string strsql =
                    "select * from " +
                        "( " +
                            "select a.*, row_number() over(order by a.studentid) rownum " +
                            "from student as a " +
                        ") b " +
                    "where b.rownum between @beginrownum and @endrownum " +
                    "order by b.rownum ";

            using (var conn = getcon())
            {
                return conn.query<student>(strsql, new { beginrownum = beginrownum, endrownum = endrownum });
            }
        }

    6.2、通用分页

create procedure [dbo].[pagelist]
     @tablename varchar(200),       --表名
     @fieldname varchar(500) = '*', --字段名
     @where varchar(100) = null,    --条件语句
     @groupby varchar(100) = null,  --分组字段
     @orderby varchar(100),         --排序字段
     @pageindex int = 1,            --当前页数
     @pagesize int = 20,            --每页显示记录数
     @totalcount int = 0 output     --总记录数
as
begin
    --sql拼接语句
    declare @sql nvarchar(4000)

    --总记录数
    set @sql='select @recordcount=count(1) from ' + @tablename
    if (isnull(@where,'')<>'')
        set @sql=@sql+' where '+@where
    else if (isnull(@groupby,'')<>'')
        set @sql=@sql+' group by '+@groupby

    exec sp_executesql @sql,n'@recordcount int output',@totalcount output

    --总页数
    declare @pagecount int
    select @pagecount=ceiling((@totalcount+0.0)/@pagesize)
    
    --简单分页
    set @sql='select * from (select row_number() over (order by '+@orderby+') as rownum,' + @fieldname + ' from '+@tablename+' as a'
    if (isnull(@where,'')<>'')
        set @sql=@sql+' where '+@where
    else if (isnull(@groupby,'')<>'')
        set @sql=@sql+' group by '+@groupby

    if (@pageindex<=0)
        set @pageindex=1
    if @pageindex>@pagecount
        set @pageindex=@pagecount
     
    declare @beginrownum int,@endrownum int  
    set @beginrownum=(@pageindex-1)*@pagesize+1
    set @endrownum=@beginrownum+@pagesize-1

    set @sql=@sql + ') as b where b.rownum between '+convert(varchar(32),@beginrownum)+' and '+convert(varchar(32),@endrownum)
    exec(@sql)
end
        /// <summary>
        /// 通用分页
        /// </summary>
        /// <returns></returns>
        public ienumerable<t> getcommonpaging<t>(string tablename, string fieldname, string where, string groupby, string orderby, int pageindex, int pagesize)
        {
            var para = new dynamicparameters();
            para.add("tablename", tablename);
            para.add("fieldname", fieldname);
            para.add("where", where);
            para.add("groupby", groupby);
            para.add("orderby", orderby);
            para.add("pageindex", pageindex);
            para.add("pagesize", pagesize);
            para.add("totalcount", dbtype: dbtype.int32, direction: parameterdirection.output);

            using (var conn = getcon())
            {
                conn.open();
                return conn.query<t>("pagelist", para, commandtype: commandtype.storedprocedure);
            }
        }