Dapper Use For Net
Dapper.Net by example
januari 6, 2012
When the team behind StackOverflow released the mini-ORM Dapper, we were enthousiastic. An ORM with performance in mind!
Microsoft’s Entity Framework is still lagging behind and feels (is) like a beast. NHibernate is a beast as well, but is usally fast with second-level caching. For simple applications or scheduled tasks, it just too much. And for poorly designed legacy databases, it works against you. When you just need to write SQL queries and want to map the results to objects, a mini ORM suffices.
StackOverflow is one of the most responsive sites I know, so its ORM performance’s is proven. Dapper’s documentation however is somewhat sparse.
Basic usage
Download the single file SqlMapper.cs and dump it in your project.
Put using Dapper in your file with queries, because Dapper extends the normal IDbConnection interface (which is somewhat of a bad practice imho).
Use your favorite way (Dependency Injection of course) of providing a IDbConnection connection named conn,just as you normally would when using a ADO.NET. Basically like so:
using (var conn = new SqlConnection(myConnectionString)) {
conn.Open();
....
}
A list of objects
Select a list of accounts from a certain webshop.
IEnumerable<Account> resultList = conn.Query<Account>(@"
SELECT *
FROM Account
WHERE shopId = @ShopId",
new { ShopId = shopId });
The Account object is for example.
public class Account {
public int? Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public int ShopId {get; set;}
}
Note that eventhough we use SELECT *, not all fields have to be present as class properties.
A single object
Account result = conn.Query<Account>(@"
SELECT *
FROM Account
WHERE Id = @Id",
new { Id = Id }).FirstOrDefault();
A dynamic object
If you’re too lazy to type out a class, you can use a dynamic object.
dynamic account = conn.Query<dynamic>(@"
SELECT Name, Address, Country
FROM Account
WHERE Id = @Id", new { Id = Id }).FirstOrDefault();
Console.WriteLine(account.Name);
Console.WriteLine(account.Address);
Console.WriteLine(account.Country);
Nice! Probably somewhat slower than if you type out the class.
A list of objects with single child object (multimap)
Imagine we want the Shop data with the Accounts as well. It is a legacy database, so the Shop’s Id is named ShopId instead of Id. This can be overcome with the ‘splitOn’ option.
public class Account {
public int? Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public int ShopId {get; set;}
public Shop Shop {get;set;}
}
public class Shop {
public int? ShopId {get;set;}
public string Name {get;set;}
public string Url {get;set;}
} var resultList = conn.Query<Account, Shop, Account>(@"
SELECT a.Name, a.Address, a.Country, a.ShopId
s.ShopId, s.Name, s.Url
FROM Account a
INNER JOIN Shop s ON s.ShopId = a.ShopId
", (a, s) => {
a.Shop = s;
return a;
},
splitOn: "ShopId"
).AsQueryable();
A parent object with its child objects
And the other way around: find the shop with all its accounts. It’s a little more complicated, as each row is given as (Shop s, Account a), but Shop s is a new object every time. So we have to remember one shop to add all accounts to.
public class Shop {
public int? Id {get;set;}
public string Name {get;set;}
public string Url {get;set;}
public IList<Account> Accounts {get;set;}
} public class Account {
public int? Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public int ShopId {get;set;}
} var lookup = new Dictionary<int, Shop>()
conn.Query<Shop, Account, Shop>(@"
SELECT s.*, a.*
FROM Shop s
INNER JOIN Account a ON s.ShopId = a.ShopId
", (s, a) => {
Shop shop;
if (!lookup.TryGetValue(s.Id, out shop)) {
lookup.Add(s.Id, shop = s);
}
if (shop.Accounts == null)
shop.Accounts = new List<Account>();
shop.Accounts.Add(a);
return shop;
},
).AsQueryable(); var resultList = lookup.Values;
I got this dapper test ParentChildIdentityAssociations: https://code.google.com/p/dapper-dot-net/source/browse/Tests/Tests.cs#1343
Insert and update
Insert and update is not part of the default Dapper file. However, these is an extension for these functions — which usually are the most tedious to maintain, so it is more than welcome.
Mark you identifier with [KeyAttribute]
public class Account {
[KeyAttribute]
public int? Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public int ShopId {get; set;}
}
And then you can create a simple Persist function:
public void Persist(IDbConnection conn, Account acc) {
if (acc.Id == null) {
SqlMapperExtensions.Insert(conn, acc);
}
else {
SqlMapperExtensions.Update(conn, acc);
}
}
Dapper Use For Net的更多相关文章
- Dapper逆天入门~强类型,动态类型,多映射,多返回值,增删改查+存储过程+事物案例演示
Dapper的牛逼就不扯蛋了,答应群友做个入门Demo的,现有园友需要,那么公开分享一下: 完整Demo:http://pan.baidu.com/s/1i3TcEzj 注 意 事 项:http:// ...
- Dapper扩展之~~~Dapper.Contrib
平台之大势何人能挡? 带着你的Net飞奔吧!http://www.cnblogs.com/dunitian/p/4822808.html#skill 上一篇文章:Dapper逆天入门~强类型,动态类型 ...
- 由Dapper QueryMultiple 返回数据的问题得出==》Dapper QueryMultiple并不会帮我们识别多个返回值的顺序
异常汇总:http://www.cnblogs.com/dunitian/p/4523006.html#dapper 今天帮群友整理Dapper基础教程的时候手脚快了点,然后遇到了一个小问题,Dapp ...
- Dapper.Contrib:GetAsync<T> only supports an entity with a [Key] or an [ExplicitKey] property
异常处理:http://www.cnblogs.com/dunitian/p/4523006.html#dapper 原来Model是这样滴 修改后是这样滴 注意点:Model里面的Table和Key ...
- Dapper where Id in的解决方案
简单记一下,一会出去有点事情~ 我们一般写sql都是==>update NoteInfo set NDataStatus=@NDataStatus where NId in (@NIds) Da ...
- ASP.NET Core 1.0 使用 Dapper 操作 MySql(包含事务)
操作 MySql 数据库使用MySql.Data程序包(MySql 开发,其他第三方可能会有些问题). project.json 代码: { "version": "1. ...
- Asp.Net Core + Dapper + Repository 模式 + TDD 学习笔记
0x00 前言 之前一直使用的是 EF ,做了一个简单的小项目后发现 EF 的表现并不是很好,就比如联表查询,因为现在的 EF Core 也没有啥好用的分析工具,所以也不知道该怎么写 Linq 生成出 ...
- 搭建一套自己实用的.net架构(3)续 【ORM Dapper+DapperExtensions+Lambda】
前言 继之前发的帖子[ORM-Dapper+DapperExtensions],对Dapper的扩展代码也进行了改进,同时加入Dapper 对Lambda表达式的支持. 由于之前缺乏对Lambda的知 ...
- mono for android中使用dapper或petapoco对sqlite进行数据操作
在mono for android中使用dapper或petapoco,很简单,新建android 类库项目,直接把原来的文件复制过来,对Connection连接报错部分进行注释和修改就可以运行了.( ...
- Dapper:The member of type SeoTKD cannot be used as a parameter Value
异常汇总:http://www.cnblogs.com/dunitian/p/4523006.html#dapper 上次说了一下Dapper的扩展Dapper.Contrib http://www. ...
随机推荐
- JSP特点
建立在servlet规范功能之上的动态网页技术. JSP文件在用户第一次请求时,会被编译成servlet,然后由servlet处理用户的请求.所以JSP可以看成运行时servlet. 1).将内容的生 ...
- BZOJ 3595: [Scoi2014]方伯伯的Oj SBT+可持久化Treap
3595: [Scoi2014]方伯伯的Oj Time Limit: 6 Sec Memory Limit: 256 MBSubmit: 102 Solved: 54[Submit][Status ...
- [BZOJ 2178] 圆的面积并 【Simpson积分】
题目链接:BZOJ - 2178 题目分析 用Simpson积分,将圆按照 x 坐标分成连续的一些段,分别用 Simpson 求. 注意:1)Eps要设成 1e-13 2)要去掉被其他圆包含的圆. ...
- edgejs
http://krasimirtsonev.com/blog/article/Real-time-chat-with-NodeJS-Socketio-and-ExpressJS https://git ...
- Palindrome
poj3974:http://poj.org/problem?id=3974 题意:求给定长度最长回文串的长度. 题解:直接套manacher,搞定. #include<iostream> ...
- 如何通过js使搜索关键词高亮
给你推荐通过jquery来实现高亮关键词.jquery.textSearch-1.0.js代码: (function($){ $.fn.textSearch =function(str,options ...
- latch free
latch free 等待事件: latch: cache buffers chains 这个等待事件其实还有另外一个重要的原因,那么就是逻辑读太高,SQL执行计划走错了导致的. 当进程想要获取锁存器 ...
- (转载)在vmware中简单配置vsftpd服务器
(转载)http://blog.chinaunix.net/uid-7453676-id-2625582.html 分类: LINUX 一 试验的前期环境搭建 系统环境:Fedora 2 软件 ...
- 网络流(最大流) CodeForces 546E:Soldier and Traveling
In the country there are n cities and m bidirectional roads between them. Each city has an army. Arm ...
- Delphi webservice 定义 转
webservice Web Services是由企业发布的完成其特定商务需求的在线应用服务,其他公司或应用软件能够通过Internet来访问并使用这项在线服务. 简介 它是一种构建应用程序的普遍 ...