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. ...
随机推荐
- Core MVC
Core MVC 配置全局路由前缀 前言 大家好,今天给大家介绍一个 ASP.NET Core MVC 的一个新特性,给全局路由添加统一前缀.严格说其实不算是新特性,不过是Core MVC特有的. 应 ...
- 学习Swift -- 泛型
泛型 泛型代码可以让你写出根据自我需求定义.适用于任何类型的,灵活且可重用的函数和类型.它的可以让你避免重复的代码,用一种清晰和抽象的方式来表达代码的意图. 泛型所解决的问题 先来看一个交换两个int ...
- java web 代码
原 30套JSP网站源代码合集 IT小白白 发布时间: 2012/12/28 14:30 阅读: 272 收藏: 3 点赞: 0 评论: 0 JSP技术是以Java语言作为脚本语言的,JSP网页为整个 ...
- C++ 利用socket实现TCP,UDP网络通讯
学习孙鑫老师的vc++深入浅出,有一段时间了,第一次接触socket说实话有点儿看不懂,第一次基本上是看他说一句我写一句完成的,第二次在看SOCKET多少有点儿感觉了,接下来我把利用SOCKET完成T ...
- Android模拟器常用命令收录
一.Linux命令 1.挂载/systme分区为读写状态 mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system 2.切换为Root用户 ...
- PL/SQL游标使用
游标是用来处理使用SELECT语句从数据库中检索到的多行记录的工具.借助游标的功能,数据库应用程序可以对一组记录逐个进行处理,每次处理一行. 游标是从数据表中提取出来的数据,以临时表的形式存放在内存中 ...
- 【HDOJ】2966 In case of failure
KD树,这东西其实在ML经常被使用,不过30s的时限还是第一次见. /* 2966 */ #include <iostream> #include <string> #incl ...
- 【HDOJ】3696 Farm Game
SPFA求最短路径.见图的时候注意逆向建图. /* 3696 */ #include <iostream> #include <queue> #include <vect ...
- bzoj1236
其实这道题目不难,主要要求我们有一个清晰地思路首先可以按位数讨论,这里我把1~9单独讨论了因为除了1位数,每个位数开头的数的开头数字1前面都是-号然后考虑位数的奇偶性当位数为奇数的时候比较简单举个例子 ...
- JavaScript高级程序设计12.pdf
第六章 面向对象的程序设计 ECMA中有两种属性:数据属性和访问器属性 数据属性的特性 [[Configurable]] 表示是否通过delete删除属性,是否重新定义属性,是否能把属性修改为访问器属 ...