转载:http://www.csdn123.com/html/itweb/20130918/125194_125199_125210.htm

.NET 轻量级 ORM 框架 - Dapper 介绍

Dapper简单介绍:

Dapper is a single file you can drop in to your project that will extend your IDbConnection interface.

Dapper是一个轻型的开源ORM类,代码就一个SqlMapper.cs文件,编译后就40多K的一个很小的Dll. 官方资料:点击这里

Dapper支持Mysql,SqlLite,Mssql2000,Mssql2005,Oracle等一系列的数据库,当然如果你知道原理也可以让它支持Mongo db

Dapper的r支持多表并联的对象。支持一对多 多对多的关系。并且没侵入性,想用就用,不想用就不用。无XML无属性。代码以前怎么写现在还怎么写。

Dapper原理通过Emit反射IDataReader的序列队列,来快速的得到和产生对象。性能提升了很多;(比采用常规的反射)

Dapper支持net2.0,3.0,3.5,4.0。不过就是要配置下。如果不知道如何配置查看我博客里的在2.0下使用3.5就可以了。

语法十分简单。并且无须迁就数据库的设计。

Dapper执行效率:

30W条数据,取其中的一个对象,和第一页前15条数据,耗时0.0906879秒。这个速度超过Datable。

官方的测试代码以及数据

Performance of SELECT mapping over 500 iterations
- POCO serialization

Method Duration Remarks
Hand coded (using a SqlDataReader) 47ms
Dapper ExecuteMapperQuery<Post> 49ms
PetaPoco 52ms Can be faster
BLToolkit 80ms
SubSonic CodingHorror 107ms
NHibernate SQL 104ms
Linq 2 SQL ExecuteQuery 181ms
Entity framework ExecuteStoreQuery 631ms

Performance of SELECT mapping over 500 iterations
- dynamic serialization

Method Duration Remarks
Dapper ExecuteMapperQuery
(dynamic)
48ms
Massive 52ms
Simple.Data 95ms

Performance of SELECT mapping over 500 iterations
- typical usage

Method Duration Remarks
Linq 2 SQL CompiledQuery 81ms Not super typical involves complex code
NHibernate HQL 118ms
Linq 2 SQL 559ms
Entity framework 859ms
SubSonic ActiveRecord.SingleOrDefault 3619ms

Dapper使用介绍:

如果你使用的是vs2012,可以使用NuGet来进行安装,会自动添加引用,使用时写入命名空间即可;

 

 using Dapper;

下面的代码可以作为使用参考:

public static readonly string sqlconnectionString
"Data
Source=xxx;Initial Catalog=Express;User ID=sa;Password=123"
;

 
public static readonly string mysqlconnectionString
@"server=xxx;database=dddd;uid=xxx;pwd=123;charset='gbk'";
 
public static SqlConnection
SqlConnection()
{
    var
connection = 
new SqlConnection(sqlconnectionString);
    connection.Open();
    return connection;
}
 
public static  MySqlConnection 
MySqlConnection()
{
    var
connection = 
new MySqlConnection(mysqlconnectionString);
    connection.Open();
    return connection;

}

调用方法

SqlConnection connection = Program.SqlConnection();

获得一个实体对象

var d = connection.Query<Dog>("select * from dog where id = 1"null).Single<Dog>();

获得实体对象结合

var dd = connection.Query<Dog>("select * from dog where id < 10", null).ToList<Dog>();

插入数据

//动态参数
connection.Execute("INSERT INTO dog (Age,Name,Weight) VALUES (@age,@name,@Weight)",
new { @age = i,@name = Guid.NewGuid().ToString(), @Weight = i }); //直接传入实体
connection.Execute("INSERT INTO dog (Age,Name,Weight) VALUES (@age,@name,@Weight)",model);
Execute a query and map the results to a strongly typed List

Note: all extension methods assume the connection is already open, they will fail if the connection is closed.

public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

Example usage:

publicclassDog

{

    publicint?Age{get;set;}

    publicGuidId{get;set;}

    publicstringName{get;set;}

    publicfloat?Weight{get;set;}

    publicintIgnoredProperty{get{return1;}}

}            

var guid =Guid.NewGuid();

var dog = connection.Query<Dog>("select Age = @Age, Id = @Id",new{Age=(int?)null,Id= guid });

dog.Count()

    .IsEqualTo(1);

dog.First().Age

    .IsNull();

dog.First().Id

    .IsEqualTo(guid);

Execute a query and map it to a list of dynamic objects

public static IEnumerable<dynamic> Query (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

This method will execute SQL and return a dynamic list.

Example usage:

 var rows = connection.Query("select 1 A, 2 B union all select 3, 4");

((int)rows[0].A)

   .IsEqualTo(1);

((int)rows[0].B)

   .IsEqualTo(2);

((int)rows[1].A)

   .IsEqualTo(3);

((int)rows[1].B)

    .IsEqualTo(4);

Execute a Command that returns no results

public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Example usage:

connection.Execute(@"

  set nocount on 

  create table #t(i int) 

  set nocount off 

  insert #t 

  select @a a union all select @b 

  set nocount on 

  drop table #t",new{a=1, b=2})

   .IsEqualTo(2);

Execute a Command multiple times

The same signature also allows you to conveniently and efficiently execute a command multiple times (for example to bulk-load data)

Example usage:

connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",

    new[]{new{ a=1, b=1},new{ a=2, b=2},new{ a=3, b=3}}

  ).IsEqualTo(3);// 3 rows inserted: "1,1", "2,2" and "3,3"

This works for any parameter that implements IEnumerable<T> for some T.

var
dd = connection.Query<Dog>(
"select
* from dog where id < 10"
null).ToList<Dog>();

Dapper 介绍的更多相关文章

  1. .NET 轻量级 ORM 框架 - Dapper 介绍

    Dapper简单介绍: Dapper is a single file you can drop in to your project that will extend your IDbConnect ...

  2. Dapper入门教程(一)——Dapper介绍

    Dapper是什么? Dpper是一款.Net平台简单(Simple)的对象映射库,并且Dapper拥有着"微型ORM之王"的称号.就速度而言与手写ADO.NET SqlDateR ...

  3. asp.net core系列 66 Dapper介绍--Micro-ORM

    一.概述 目前对于.net的数据访问ORM工具很多,EF和EF Core是一个重量级的框架.最近在搭建新的项目架构,来学习一下轻量级的数据访问ORM工具Dapper.Dapper支持SQL Serve ...

  4. 1、Dapper介绍

    1.Dapper是一个轻量级的O/R框架,性能强劲,支持原生sql与模型对象混合写法,通过DapperExtension插件可以实现纯模型的操作(零Sql)语句. 2.创建VS 项目,添加相关的依赖包 ...

  5. Dapper入门使用,代替你的DbSQLhelper

    Dapper介绍 Dapper是.Net下的一个轻量级ORM框架.在小型工具向的项目下,使用Dapper会使数据库操作层代码更加优雅. Dapper的使用 在项目中使用引用Dapper非常简单,你可以 ...

  6. Dapper系列之一:Dapper的入门(多表批量插入)

    Dapper介绍  简介:      不知道博客怎么去写去排版,查了好多相关博客,也根据自己做过项目总结,正好最近搭个微服务框架,顺便把搭建微服务框架所运用的知识都进行博客梳理,为了以后复习,就仔细琢 ...

  7. 1.NetDh框架之数据库操作层--Dapper简单封装,可支持多库实例、多种数据库类型等(附源码和示例代码)

    1.NetDh框架开始的需求场景 需求场景: 1.之前公司有不同.net项目组,有的项目是用SqlServer做数据库,有的项目是用Oracle,后面也有可能会用到Mysql等,而且要考虑后续扩展成主 ...

  8. windows server 证书的颁发与IIS证书的使用 Dapper入门使用,代替你的DbSQLhelper Asp.Net MVC中Action跳转(转载)

    windows server 证书的颁发与IIS证书的使用   最近工作业务要是用服务器证书验证,在这里记录下一. 1.添加服务器角色 [证书服务] 2.一路下一步直到证书服务安装完成; 3.选择圈选 ...

  9. C# Dapper 的简单实用

    首先引入dapper  PM>Install-Package Dapper -Version 2.0.4 (可能会出现因版本问题而安装失败详情见官网:https://stackexchange. ...

随机推荐

  1. ShellExecute使用详解

    ShellExecute命令 ⑴ 函数原型: HINSTANCE ShellExecute(HWND hwnd, LPCTSTR lpOperation, LPCTSTR lpFile, LPCTST ...

  2. BZOJ3149 CTSC2013 复原 搜索

    传送门 \(N \leq 20\)很适合暴搜-- 第二问最大独立集裸题,\(O(2^NN)\)的算法都能过-- 考虑第一问,使用搜索寻找可行解 每一次枚举一条弦的两个端点,通过位运算计算与其相交的弦的 ...

  3. Linux Shell完成Qt程序的自动部署

    #!/bin/sh #取当前脚本的绝对路径 srcDir=$(cd ")";pwd) #设置库所在路径 libDir=${srcDir}"/J1900RunLib/*&q ...

  4. UWP简单示例(二):快速开始你的3D编程

    准备 IDE:Visual Studio 开源库:GitHub.SharpDx 入门示例:SharpDX_D3D12HelloWorld 为什么选择 SharpDx? SharpDx 库与 UWP 兼 ...

  5. C#断点续传下载。

    断点续传 最近在优化之前的下载流程,仅此篇幅留作笔记之用,日后其他研究此类问题的伙伴可以马上了解原理和开发,减少开发成本. 原理:断点续传目前比较通用的是使用HTTP续传方式,相关的资料可以通过访问: ...

  6. [UWP 自定义控件]了解模板化控件(5):VisualState

    1. 功能需求 使用TemplatePart实现上篇文章的两个需求(Header为空时隐藏HeaderContentPresenter,鼠标没有放在控件上时HeaderContentPresent半透 ...

  7. 一个很好用的在线编辑、展示、分享、交流JavaScript 代码的平台

    在发表博客时,有一些代码只能粘贴进去,而不能看到代码运行的效果,需要读者把代码粘贴进自己的编辑器,然后再运行看效果,这是一件很耗时的事情 在平时百度的时候,我发现一些网站可以在线预览功能,而且可以在线 ...

  8. 手机APP自动化之uiautomator2 +python3 UI自动化

    题记: 之前一直用APPium直到用安卓9.0  发现uiautomatorviewer不支持安卓 9.0,点击截屏按钮 一直报错,百度很久解决方法都不可以,偶然间看见有人推荐:uiautomator ...

  9. Python 可调用对象

    除了用户定义的函数,调用运算符(即 ())还可以应用到其他对象上.如果想判断对象能否调用,可以使用内置的 callable() 函数.Python 数据模型文档列出了 7 种可调用对象.(1)用户定义 ...

  10. Linux课题实践五——字符集总结与分析

    Linux课题实践三——字符集总结与分析 20135318  刘浩晨 字符是各种文字和符号的总称,包括各国家文字.标点符号.图形符号.数字等.字符集是多个字符的集合,字符集种类较多,每个字符集包含的字 ...