轻型ORM--Dapper
推荐理由:Dapper只有一个代码文件,完全开源,你可以放在项目里的任何位置,来实现数据到对象的ORM操作,体积小速度快:)
Google Code下载地址:
http://code.google.com/p/dapper-dot-net/
https://github.com/SamSaffron/dapper-dot-net
授权协议:Apache License 2.0
Dapper - a simple object mapper for .Net
Official Github clone: https://github.com/SamSaffron/dapper-dot-net
Documentation you can improve
The Dapper tag wiki on Stack Overflow can be improved by any Stack Overflow users. Feel free to add relevant information there.
Features
Dapper is a single file you can drop in to your project that will extend your IDbConnection interface.
It provides 3 helpers:
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.
Performance
A key feature of Dapper is performance. The following metrics show how long it takes to execute 500 SELECT statements against a DB and map the data returned to objects.
The performance tests are broken in to 3 lists:
- POCO serialization for frameworks that support pulling static typed objects from the DB. Using raw SQL.
- Dynamic serialization for frameworks that support returning dynamic lists of objects.
- Typical framework usage. Often typical framework usage differs from the optimal usage performance wise. Often it will not involve writing SQL.
Performance of SELECT mapping over 500 iterations - POCO serialization
Method | Duration | Remarks |
Hand coded (using a SqlDataReader) | 47ms | |
Dapper ExecuteMapperQuery<Post> | 49ms | |
ServiceStack.OrmLite (QueryById) | 50ms | |
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 |
Performance benchmarks are available here: http://code.google.com/p/dapper-dot-net/source/browse/Tests/PerformanceTests.cs , Feel free to submit patches that include other ORMs - when running benchmarks, be sure to compile in Release and not attach a debugger (ctrl F5)
Parameterized queries
Parameters are passed in as anonymous classes. This allow you to name your parameters easily and gives you the ability to simply cut-and-paste SQL snippets and run them in Query analyzer.
new{A =1, B ="b"}// A will be mapped to the param @A, B to the param @B
Advanced features
List Support
Dapper allow you to pass in IEnumerable<int> and will automatically parameterize your query.
For example:
connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[] { 1, 2, 3 });
Will be translated to:
select*from(select1asIdunion all select2union all select3)as X whereIdin(@Ids1,@Ids2,@Ids3)" // @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3
Buffered vs Unbuffered readers
Dapper's default behavior is to execute your sql and buffer the entire reader on return. This is ideal in most cases as it minimizes shared locks in the db and cuts down on db network time.
However when executing huge queries you may need to minimize memory footprint and only load objects as needed. To do so pass, buffered: false into the Query method.
Multi Mapping
Dapper allows you to map a single row to multiple objects. This is a key feature if you want to avoid extraneous querying and eager load associations.
Example:
var sql =
@"select * from #Posts p
left join #Users u on u.Id = p.OwnerId
Order by p.Id";
var data = connection.Query<Post,User,Post>(sql,(post, user)=>{ post.Owner= user;return post;});
var post = data.First();
post.Content.IsEqualTo("Sams Post1");
post.Id.IsEqualTo(1);
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo(99);
important note Dapper assumes your Id columns are named "Id" or "id", if your primary key is different or you would like to split the wide row at point other than "Id", use the optional 'splitOn' parameter.
Multiple Results
Dapper allows you to process multiple result grids in a single query.
Example:
var sql =
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id";
using(var multi = connection.QueryMultiple(sql,new{id=selectedId}))
{
var customer = multi.Read<Customer>().Single();
var orders = multi.Read<Order>().ToList();
var returns = multi.Read<Return>().ToList();
...
}
Stored Procedures
Dapper supports fully stored procs:
var user = cnn.Query<User>("spGetUser",new{Id=1},
commandType:CommandType.StoredProcedure).First();}}}
If you want something more fancy, you can do:
var p =newDynamicParameters();
p.Add("@a",11);
p.Add("@b", dbType:DbType.Int32, direction:ParameterDirection.Output);
p.Add("@c", dbType:DbType.Int32, direction:ParameterDirection.ReturnValue); cnn.Execute("spMagicProc", p, commandType: commandType.StoredProcedure); int b = p.Get<int>("@b");
int c = p.Get<int>("@c");
Ansi Strings and varchar
Dapper supports varchar params, if you are executing a where clause on a varchar column using a param be sure to pass it in this way:
Query<Thing>("select * from Thing where Name = @Name",new{Name=newDbString{Value="abcde",IsFixedLength=true,Length=10,IsAnsi=true});
On Sql Server it is crucial to use the unicode when querying unicode and ansi when querying non unicode.
轻型ORM--Dapper的更多相关文章
- ASP .Net Core 使用 Dapper 轻型ORM框架
一:优势 1,Dapper是一个轻型的ORM类.代码就一个SqlMapper.cs文件,编译后就40K的一个很小的Dll. 2,Dapper很快.Dapper的速度接近与IDataReader,取列表 ...
- .net平台性能很不错的轻型ORM类Dapper
dapper只有一个代码文件,完全开源,你可以放在项目里的任何位置,来实现数据到对象的ORM操作,体积小速度快. 使用ORM的好处是增.删.改很快,不用自己写sql,因为这都是重复技术含量低的工作,还 ...
- 使用轻量级ORM Dapper进行增删改查
项目背景 前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET.微软的EF.NH等.再跟经理讨论后,经理强调不要用Ef,NH做ORM,后期的sql优化不好做,公司 ...
- 给力分享新的ORM => Dapper( 转)
出处:http://www.cnblogs.com/sunjie9606/archive/2011/09/16/2178897.html 最近一直很痛苦,想选一个好点的ORM来做项目,实在没遇到好的. ...
- 搭建一套自己实用的.net架构(3)续 【ORM Dapper+DapperExtensions+Lambda】
前言 继之前发的帖子[ORM-Dapper+DapperExtensions],对Dapper的扩展代码也进行了改进,同时加入Dapper 对Lambda表达式的支持. 由于之前缺乏对Lambda的知 ...
- C#轻型ORM框架PetaPoco试水
近端时间从推酷app上了解到C#轻微型的ORM框架--PetaPoco.从github Dapper 开源项目可以看到PetaPoco排第四 以下是网友根据官方介绍翻译,这里贴出来. PetaPoco ...
- NFine - 全球领先的快速开发平台 Dapper Chloe
http://www.nfine.cn/ 技术交流群:549652099 出处:http://www.cnblogs.com/huanglin/ 分享一个轻型ORM--Dapper选用理由 Chloe
- C# 使用 Dapper 实现 SQLite 增删改查
Dapper 是一款非常不错的轻型 ORM 框架,使用起来非常方便,经常使用 EF 框架的人几乎感觉不到差别,下面是自己写的 Sqlite 通用帮助类: 数据连接类: public class SQL ...
- Asp.Net Core + Dapper + Repository 模式 + TDD 学习笔记
0x00 前言 之前一直使用的是 EF ,做了一个简单的小项目后发现 EF 的表现并不是很好,就比如联表查询,因为现在的 EF Core 也没有啥好用的分析工具,所以也不知道该怎么写 Linq 生成出 ...
随机推荐
- C# 闭包问题
C# 闭包问题-你被”坑“过吗? 引言 闭包是什么?以前看面试题的时候才发现这个名词. 闭包在实际项目中会有什么问题?现在就让我们一起来看下这个不太熟悉的名词. 如果在实际工作中用到了匿名函数和lam ...
- 测试数据库sql声明效率
书写sql当被发现的声明.对于所期望的结果通常是更好地执行. 当面对这些实现的时候如何选择它的最好的,相对来说?这导致了这个博客的话题,如何测试sql效率 以下介绍几种sql语句測试效率的方法,大多数 ...
- Computer Science 学习第四章--CPU 指令集和指令处理
Instruction set Y86 指令集 运算符:addl, subl, andl, and xorl 跳转符:jmp,jle,jl,je,jne,jge, andjg 条件符:cmovle, ...
- “NET网络”进行中,多管齐下的人才力挫“”粗俗
随着互联网的迅猛发展,一些不太干净.低俗的甚至色情的内容不断浮现.不仅严重影响了我们的上网体验,也成为扰乱互联网正常秩序的罪魁祸首,部分不法内容甚至给网民造成了一定的財产损失.在这样的 ...
- .NET反编译之Reflector基础示例
这几日由于公司需要, 看了些.NET反编译技巧,特地和大家分享下 .NET反编译工具很多,Reflector是其中一个很优秀的工具,所以就用它来进行反编译工作了.今天我们就用"繁星代码生成器 ...
- 基于hadoop的电影推荐结果可视化
数据可视化 1.数据的分析与统计 使用sql语句进行查询,获取所有数据的概述,包括电影数.电影类别数.人数.职业种类.点评数等. 2.构建数据可视化框架 这里使用了前端框架Bootstrap进行前端的 ...
- Oracle 多行转多列
Oracle 多行转多列,列值转为列名 前段时间做调查问卷,客户创建自定义问卷内容,包括题目和选项内容; 之后需要到处问卷明细,,,,麻烦来咯 于是到网上到处搜索,没有直接结果;于是又找各种相似的 ...
- twitter接口开发
前一阵子研究了下twitter接口,发现网上的资料不是很多.遂花了些心血,终于有所收获~ 现在有时间赶紧整理出来便于自己以后查阅,也想帮助有困难的同学们.废话不多说,现在就以最简洁的方式开始了.注意: ...
- 在ASP.NET 5应用程序中的跨域请求功能详解
在ASP.NET 5应用程序中的跨域请求功能详解 浏览器安全阻止了一个网页中向另外一个域提交请求,这个限制叫做同域策咯(same-origin policy),这组织了一个恶意网站从另外一个网站读取敏 ...
- adb这点小事——远程adb调试
欢迎转载.转载请注明:http://blog.csdn.net/zhgxhuaa 1. 前言 1.1. 写在前面的话 在之前的一篇文章<360电视助手实现研究>中介绍了在局域网内直接 ...