C# 数据操做系列 - 17 Dapper ——号称能够与ADO.NET 同台飙车的ORM

0. 前言

以前四篇介绍了一个国内开发者开发的优秀框架SqlSugar,给咱们眼前一亮的感受。这一篇,咱们将试试另外一个出镜率比较高的ORM框架-Dapper。sql

Dapper是一个轻量级的ORM框架,其以高速、简单易用为特色。在某些时候,效率甚至能够与ADO.NET 媲美。那么,吹得天花乱坠,就让咱们实际看看它的表现吧。数据库

1. 开始使用

照例,先建立一个项目:DapperDemoc#

dotnet new console --name DapperDemo

而后切换到目录里:缓存

cd DapperDemo

添加包支持:bash

dotnet add package Dapper

若是不出意外的话,目前项目中已经安装好了Dapper。如今就让咱们开始愉快的使用吧。app

首先,须要注意的一点是,与其余的ORM框架不一样的是,Dapper须要咱们手动建立一个IConnection。Dapper的全部操做都是依托于IConnection来操做,并且Dapper将其支持的方法封装成了IConnection的扩展方法。框架

因此,在使用以前咱们须要先建立一个IConnection。为了方便演示,我把以前SqlSugar演示用过的测试数据库拿过来了,是一个SQLite,因此咱们须要先安装一个SQLite的驱动:测试

dotnet add package Microsoft.Data.SQLite

在Program.cs中引入两个包:优化

using Microsoft.Data.Sqlite;
using Dapper;

在Main方法里建立一个IConnection:this

using(var connection = new SqliteConnection("Data Source=./demo.db"))
{
    
}

2. 多数据查询

Dapper的查询至关简单:

var result = connection.Query("select * from Persion");

传入一个SQL语句,返回一个可枚举对象。若是不指定类型,将返回类型为dynamic的列表。咱们来看一下Query方法的相关声明:

public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null);

public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null);

public static IEnumerable<TReturn> Query<TReturn>(this IDbConnection cnn, string sql, Type[] types, Func<object[], TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null);

咱们就以最经常使用的三个为例,给大伙分析一下参数以及调用方式:

  • cnn 一个数据库链接,因此Dapper不负责管理数据库链接,这部分由咱们手动管理
  • sql 传入的SQL语句,Dapper以IDbConnection为基础,以SQL为执行命令,因此必须咱们来传入SQL语句
  • param 一个能够为Null的Object类型,表示SQL的参数化,Dapper对参数化作了一些优化,在SQL的参数化里,参数名映射到了object的属性上。
  • transaction 表示是否有IConnection级别的事务,默认为null,传入后该指令会被事务包含
  • buffered 缓存
  • commandTimeout 命令执行是否超时以及超时时间
  • commandType 表示命令模式 有 Text 普通模式,StoredProcedure 存储过程 ,TableDirect 表查询
  • splitOn 默认状况下以Id 做为两个对象之间的区分

3. 单数据查询

Dapper在数据查询方面不只支持集合做为查询结果,还能够获取单个数据。

一共有四种方式获取单数据:

public static T QueryFirst<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);
public static T QueryFirstOrDefault<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

QueryFirst 表示获取第一条查询结果,若是没有结果,则会抛出一个异常。

QueryFirstOrDefault 与QueryFirst同样,但不一样的是,若是没有则不会抛出异常,而是直接返回一个该类型的默认值,数值类型的默认值为(0),引用类型的默认值为Null。

public static T QuerySingle<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);
public static T QuerySingleOrDefault<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

QuerySingle也能查询单条数据做为结果,但与QueryFirst不一样的是QuerySingle查询时,若是数据存在多行将会抛出异常,若是不想要异常则可使用QuerySingleOrDefault做为查询方法。

4. QueryMultiple

这个另一种查询方式,对于SQL语句来讲,没有明显的限制,因此咱们有时候能够传入多个查询SQL语句进去,而后分别获取来自各个表的查询数据:

string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = @InvoiceID;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
    {
        var invoice = multi.Read<Invoice>().First();
        var invoiceItems = multi.Read<InvoiceItem>().ToList();
    }
}

看一下它的基本参数和方法声明:

public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

这个方法返回一个GridReader,经过Read方法获取须要的数据。

5. 不仅是查询

Dapper固然不仅有查询这一项功能,Dapper支持使用存储过程、insert、update、delete等其余的SQL语句进行操做数据库。使用方式:

string sql = "Invoice_Insert";

using (var connection = My.ConnectionFactory())
{
    var affectedRows = connection.Execute(sql,
        new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
        commandType: CommandType.StoredProcedure);
    var affectedRows2 = connection.Execute(sql,
        new[]
        {
            new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_1"},
            new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_2"},
            new {Kind = InvoiceKind.StoreInvoice, Code = "Many_Insert_3"}
        },
        commandType: CommandType.StoredProcedure
    );
}

示例就是使用存储过程的例子。

string sql = "INSERT INTO Customers (CustomerName) Values (@CustomerName);";

using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
    var affectedRows = connection.Execute(sql, new {CustomerName = "Mark"});

    Console.WriteLine(affectedRows);

    var customer = connection.Query<Customer>("Select * FROM CUSTOMERS WHERE CustomerName = 'Mark'").ToList();

    FiddleHelper.WriteTable(customer);
}
//== 屡次插入
string sql = "INSERT INTO Customers (CustomerName) Values (@CustomerName);";

using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
    connection.Open();

    var affectedRows = connection.Execute(sql,
    new[]
    {
    new {CustomerName = "John"},
    new {CustomerName = "Andy"},
    new {CustomerName = "Allan"}
    }
);

这是执行插入的示例。

string sql = "UPDATE Categories SET Description = @Description WHERE CategoryID = @CategoryID;";

using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{            
    var affectedRows = connection.Execute(sql,new {CategoryID = 1, Description = "Soft drinks, coffees, teas, beers, mixed drinks, and ales"});

    Console.WriteLine(affectedRows);
}

更新。

string sql = "DELETE FROM Customers WHERE CustomerID = @CustomerID";

using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{            
    var affectedRows = connection.Execute(sql, new {CustomerID = 1});

    Console.WriteLine(affectedRows);
}

删除。

Execute没什么好说的,基本就是执行SQL语句的形式完成增删改为等操做。

值得注意的是:

public static IDataReader ExecuteReader(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

返回一个IDataReader实例,这个实例能够给DataTable填充数据,使用方法以下:

DataTable table = new DataTable();
table.Load(reader);

以及:

public static T ExecuteScalar<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

这个方法是返回查询结果的第一行第一列的元素。

6. 总结

若是单说Dapper的话,并无太多好说的。不过Dapper是真的快,在实际开发中有时候会用Dapper做为EF Core的一个补充。

固然了,Dapper还有不少其余的插件,使用那些插件能够为Dappe带来非通常的提高。咱们下一篇将介绍一下Dapper的插件。

更多内容烦请关注 个人博客《高先生小屋》

file

相关文章
相关标签/搜索