转载: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>();

最新文章

  1. 【腾讯Bugly干货分享】OCS——史上最疯狂的iOS动态化方案
  2. Spring多种注入方式及注解实现DI
  3. Firefox 及其 插件“个性化设置”备份
  4. matlab 获取鼠标位置
  5. C++Builder 中 Enter键或者Tab键无效
  6. JavaScript关闭窗口的同时打开新页面的方法
  7. Windows Internals学习笔记(三)Procdump的使用
  8. android之ExpandableListActivity
  9. iOS中使用FMDB事务批量更新数据库
  10. centos 软件安装 删除
  11. var t = a&amp;&amp;b;的问题
  12. 微软 Build 2017 开发者大会:Azure 与 AI 的快速发展
  13. JavaScript实现一个复数类
  14. LeetCode - 661. Image Smoother
  15. EBS中使用JAVA方式发送HTML格式邮件
  16. 大数据量下DataTable To List效率对比
  17. Dockerfile的 RUN和CMD
  18. Apollo 2 如何支持 @Value 注解自动更新
  19. &lt;sdoi2017&gt;树点涂色
  20. lubuntu16.04 安装过程以及ssd测试模型的环境配置

热门文章

  1. Luogu4630 APIO2018 Duathlon 圆方树、树形DP
  2. hibernate 解决 java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration
  3. 案例学python——案例一:抓图
  4. copy constructor
  5. webpack笔记
  6. 运维中的日志切割操作梳理(Logrotate/python/shell脚本实现)
  7. Mysql优化系列(1)--Innodb重要参数优化
  8. OpenStack构架知识梳理
  9. Gerrit上分支操作记录(创建分支、删除分支)
  10. PHP 文件写入和读取(必看篇)