Dapper进行增删改查 z
http://www.cnblogs.com/huangkaiyan10/p/4640548.html
项目背景
前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET、微软的EF、NH等。再跟经理讨论后,经理强调不要用 Ef,NH做ORM,后期的sql优化不好做,公司也没有人对EF,Nh 等orm优化比较熟悉的。强调说的,我们的项目要做的得简单,可以使用ADO.NET 写原始的sql。但我自己还是喜欢ORM的,它可以提高数据访问层的开发。有一天,在订阅张善友 doNet跨平台微信公众号里,看到Dapper的推荐。了解之后,我自己喜欢喜欢Dapper,可以满足我这个项目的经理的要求,同时Dapper 对数据库的访问能做到Ado.net一样快。
下面的链接是Dapper 在github的地址 https://github.com/StackExchange/dapper-dot-net。
使用 Dapper 进行简单增删改查示例
1、首先根据数据库表定义实体对象, 这个工作完全可以使用T4、Nvelocity或者RazorEngine 写一个代码生成器根据数据库表对象自动生成数据库表实体对象。这里我自己根据表写了一个对象
[Table("UserRole")]
public class UserRoleDbEntity:DbEntityModelBase
{
[Description("用户编号,来自用户表")]
public int UserId
{
get;
set;
}
[Description("角色编号,来自于角色表")]
public int RoleId
{
get;
set;
}
/// <summary>
/// 备注:AuthorityEnum.AuthorityValue 的取值范围是根据 AuthorityEnum位运算 或 与 的结果集;不可随意赋值
/// </summary>
[Description("权限值")]
public int AuthorityValue { get; set; }
/// <summary>
/// 根据 AuthorityEnum 枚举值生成的描述
/// </summary>
[Description("权限描述")]
public string AuthorityDescription { get; set; }
}
/// <summary>
/// 所有DbEntityModel项目中的实体必须继承DbEntityModelBase或其子类,使用supperType模式控制共有子类的行为或者状态,此项目中的类根据数据库基本表或者视图保持基本一致
/// </summary>
public abstract class DbEntityModelBase
{
[Description("Guid标识")]
public string GuidMark
{
get;
set;
}
[Description("自增Id列")]
public int Id
{
get;
set;
}
[Description("排序,倒序")]
public int Sort
{
get;
set;
}
}
2. 在DAL层就可以使用实体对象传参 或者作为返回值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OnlineExercise.DbAccess;
using Dapper;
using System.Configuration;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using OnlineExercise.DbEntityModel;
using OnlineExercise.Log;
using OnlineExercise.Infrastructrue; namespace OnlineExercise.DbAccess.SysAdminModule
{
public class UserRoleDB:DalBase<UserRoleDB>
{
public int AddUserRole(UserRoleDbEntity model)
{
int affecgtRow = 0;
string sql = @"INSERT INTO `userrole`
(`GuidMark`,
`UserId`,
`RoleId`,
`AuthorityValue`,
`AuthorityDescription`)
VALUES (@GuidMark,
@UserId,
@RoleId,
@AuthorityValue,
@AuthorityDescription);";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, model);
}
return affecgtRow;
} public int UpdateUserRoleByRoleIdAndUserId(UserRoleDbEntity model)
{
int affecgtRow = 0;
string sql = @"UPDATE `userrole`
SET `AuthorityValue` = @AuthorityValue,
`AuthorityDescription` = @AuthorityDescription
WHERE `UserId` = @UserId
AND `RoleId` = @RoleId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, model);
}
return affecgtRow;
} public int UpdateUserRoleByRoleId(UserRoleDbEntity model)
{
int affecgtRow = 0;
string sql = @"UPDATE `userrole`
SET `AuthorityValue` = @AuthorityValue,
`AuthorityDescription` = @AuthorityDescription
WHERE `RoleId` = @RoleId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, model);
}
return affecgtRow;
} public int UpdateUserRoleByUserId(UserRoleDbEntity model)
{
int affecgtRow = 0;
string sql = @"UPDATE `userrole`
SET `AuthorityValue` = @AuthorityValue,
`AuthorityDescription` = @AuthorityDescription
WHERE `UserId` = @UserId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, model);
}
return affecgtRow;
} public List<UserRoleDbEntity> GetUserRoleListByRoleId(UserRoleDbEntity model)
{
List<UserRoleDbEntity> modelList = null;
string sql = @"SELECT
`Id`,
`GuidMark`,
`sort`,
`UserId`,
`RoleId`,
`AuthorityValue`,
`AuthorityDescription`
FROM `userrole`
WHERE RoleId=@RoleId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
modelList = conn.Query<UserRoleDbEntity>(sql, model).ToList<UserRoleDbEntity>();
}
return modelList;
} public List<UserRoleDbEntity> GetUserRoleListByUserId(string userId)
{
List<UserRoleDbEntity> modelList = null;
string sql = @"SELECT
`Id`,
`GuidMark`,
`sort`,
`UserId`,
`RoleId`,
`AuthorityValue`,
`AuthorityDescription`
FROM `userrole`
WHERE UserId=@UserId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
modelList = conn.Query<UserRoleDbEntity>(sql, new { UserId =userId}).ToList<UserRoleDbEntity>();
}
return modelList;
} public List<UserRoleDbEntity> GetUserRoleListByRoleIdAndUserId(UserRoleDbEntity model)
{
List<UserRoleDbEntity> modelList = null;
string sql = @"SELECT
`Id`,
`GuidMark`,
`sort`,
`UserId`,
`RoleId`,
`AuthorityValue`,
`AuthorityDescription`
FROM `userrole`
WHERE RoleId=@RoleId and UserId=@UserId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
modelList = conn.Query<UserRoleDbEntity>(sql, model).ToList<UserRoleDbEntity>();
}
return modelList;
} public int DeleteUserRoleByUserId(string userId)
{
int affecgtRow = 0;
string sql = @"DELETE
FROM `userrole`
WHERE `UserId` = @UserId";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, new { UserId = userId });
}
return affecgtRow;
} public int DeleteUserRoleByRoleId(string roleId)
{
int affecgtRow = 0;
string sql = @"DELETE
FROM `userrole`
WHERE `RoleId` = @RoleId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, new { RoleId = roleId }); }
return affecgtRow;
} public DataTable GetRoleInfoByUserId(string userId)
{
DataTable dt = null; string sql = @"SELECT b.*,a.userid,c.name as userName FROM userrole AS a
INNER JOIN role AS b ON a.roleid=b.id
INNER JOIN USER AS c ON c.id=a.userid
WHERE a.userid=@userid;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
IDataReader reader = conn.ExecuteReader(sql, new { userid=userId });
dt = CoreUtil.DataReader2Table(reader);
reader.Dispose();
} return dt;
} }
}
Dapper的优势
1、Dapper是一个轻型的ORM类
2、 Dapper语法简单,如果你喜欢写原始的sql,你一定喜欢Dapper。同时团队人员也很容易上手
3、Dapper 速度快,速度接近ADO.NET访问数据库的效率。
4、多数据库切换方便
public int UpdateUserRoleByRoleId(UserRoleDbEntity model)
{
int affecgtRow = 0;
string sql = @"UPDATE `userrole`
SET `AuthorityValue` = @AuthorityValue,
`AuthorityDescription` = @AuthorityDescription
WHERE `RoleId` = @RoleId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, model);
}
return affecgtRow;
}
这里mysql如果要切换为Sql Server ,只要修改链接 MySqlConnection---》SqlConnection。
Dapper更多特性
1、支持动态dynamic绑定
var rows = connection.Query("select 1 A, 2 B union all select 3, 4");
((int)rows[].A)
.IsEqualTo();
((int)rows[].B)
.IsEqualTo();
((int)rows[].A)
.IsEqualTo();
((int)rows[].B)
.IsEqualTo();
2、支持批量插入
connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
new[] { new { a=, b= }, new { a=, b= }, new { a=, b= } }
).IsEqualTo(); // 3 rows inserted: "1,1", "2,2" and "3,3"
3、支持多表关联
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();
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo();
4、支持多结果查询
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();
...
}
5 支持存储过程
var user = cnn.Query<User>("spGetUser", new {Id = },
commandType: CommandType.StoredProcedure).SingleOrDefault();
// 你还可以获取存储过程out参数的输出值或者返回值
var p = new DynamicParameters();
p.Add("@a", );
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");
6、参数自动绑定
new {A = 1, B = "b"} // A will be mapped to the param @A, B to the param @B
看到Dapper那么特性,觉得使用Dapper非常方便,使用也非常方便,扩展性也非常高。 当我用Dapper写一个demo给项目经理看的时候,项目经理就同意使用
Dapper 作为ORM 进行数据访问层的开发。从此就爱上了Dapper。
希望这篇文章给你带来对Dapper清晰的了解。
项目背景
前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET、微软的EF、NH等。再跟经理讨论后,经理强调不要用 Ef,NH做ORM,后期的sql优化不好做,公司也没有人对EF,Nh 等orm优化比较熟悉的。强调说的,我们的项目要做的得简单,可以使用ADO.NET 写原始的sql。但我自己还是喜欢ORM的,它可以提高数据访问层的开发。有一天,在订阅张善友 doNet跨平台微信公众号里,看到Dapper的推荐。了解之后,我自己喜欢喜欢Dapper,可以满足我这个项目的经理的要求,同时Dapper 对数据库的访问能做到Ado.net一样快。
下面的链接是Dapper 在github的地址 https://github.com/StackExchange/dapper-dot-net。
使用 Dapper 进行简单增删改查示例
1、首先根据数据库表定义实体对象, 这个工作完全可以使用T4、Nvelocity或者RazorEngine 写一个代码生成器根据数据库表对象自动生成数据库表实体对象。这里我自己根据表写了一个对象

[Table("UserRole")]
public class UserRoleDbEntity:DbEntityModelBase
{
[Description("用户编号,来自用户表")]
public int UserId
{
get;
set;
}
[Description("角色编号,来自于角色表")]
public int RoleId
{
get;
set;
}
/// <summary>
/// 备注:AuthorityEnum.AuthorityValue 的取值范围是根据 AuthorityEnum位运算 或 与 的结果集;不可随意赋值
/// </summary>
[Description("权限值")]
public int AuthorityValue { get; set; }
/// <summary>
/// 根据 AuthorityEnum 枚举值生成的描述
/// </summary>
[Description("权限描述")]
public string AuthorityDescription { get; set; }
}
/// <summary>
/// 所有DbEntityModel项目中的实体必须继承DbEntityModelBase或其子类,使用supperType模式控制共有子类的行为或者状态,此项目中的类根据数据库基本表或者视图保持基本一致
/// </summary>
public abstract class DbEntityModelBase
{
[Description("Guid标识")]
public string GuidMark
{
get;
set;
}
[Description("自增Id列")]
public int Id
{
get;
set;
}
[Description("排序,倒序")]
public int Sort
{
get;
set;
}
}

2. 在DAL层就可以使用实体对象传参 或者作为返回值
Dapper的优势
1、Dapper是一个轻型的ORM类
2、 Dapper语法简单,如果你喜欢写原始的sql,你一定喜欢Dapper。同时团队人员也很容易上手
3、Dapper 速度快,速度接近ADO.NET访问数据库的效率。
4、多数据库切换方便
public int UpdateUserRoleByRoleId(UserRoleDbEntity model)
{
int affecgtRow = 0;
string sql = @"UPDATE `userrole`
SET `AuthorityValue` = @AuthorityValue,
`AuthorityDescription` = @AuthorityDescription
WHERE `RoleId` = @RoleId;";
using (IDbConnection conn = new MySqlConnection(GlobalVariablesManager.G_Strconn))
{
affecgtRow = conn.Execute(sql, model);
}
return affecgtRow;
}
这里mysql如果要切换为Sql Server ,只要修改链接 MySqlConnection---》SqlConnection。
Dapper更多特性
1、支持动态dynamic绑定

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

2、支持批量插入
connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
new[] { new { a=, b= }, new { a=, b= }, new { a=, b= } }
).IsEqualTo(); // 3 rows inserted: "1,1", "2,2" and "3,3"
3、支持多表关联

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();
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo();

4、支持多结果查询

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();
...
}

5 支持存储过程

var user = cnn.Query<User>("spGetUser", new {Id = },
commandType: CommandType.StoredProcedure).SingleOrDefault();
// 你还可以获取存储过程out参数的输出值或者返回值
var p = new DynamicParameters();
p.Add("@a", );
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");

6、参数自动绑定
new {A = , B = "b"} // A will be mapped to the param @A, B to the param @B
看到Dapper那么特性,觉得使用Dapper非常方便,使用也非常方便,扩展性也非常高。 当我用Dapper写一个demo给项目经理看的时候,项目经理就同意使用
Dapper 作为ORM 进行数据访问层的开发。从此就爱上了Dapper。
希望这篇文章给你带来对Dapper清晰的了解。同时如果这文章给你到来了帮助,也别忘了帮忙推荐。
Dapper进行增删改查 z的更多相关文章
- 使用轻量级ORM Dapper进行增删改查
项目背景 前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET.微软的EF.NH等.再跟经理讨论后,经理强调不要用Ef,NH做ORM,后期的sql优化不好做,公司 ...
- Dapper.Contrib——更加优雅地使用Dapper进行增删改查
简介 Dapper是介于Entity framework与ADO的折中选择.既满足手写查询的高性能需求,又简化了数据库对象映射为内存对象的繁杂工作.Dapper.Contrib是对Dapper的进一步 ...
- Dapper基本增删改查
说明: 1.在using语句块中不用dbConnection.Open(),因为Execute方法中会Open,并且在执行完成会Close. 2.在Ado.Net中要手动Open,在Using语句块中 ...
- .net Core+Dapper MySQL增删改查
新建一个用户表,以该有为例 1.Model层 public class TuiUsers { public int id { get; set; } public string userName { ...
- Dapper逆天入门~强类型,动态类型,多映射,多返回值,增删改查+存储过程+事物案例演示
Dapper的牛逼就不扯蛋了,答应群友做个入门Demo的,现有园友需要,那么公开分享一下: 完整Demo:http://pan.baidu.com/s/1i3TcEzj 注 意 事 项:http:// ...
- 在C#的控制台应用中使用Dapper链接MySQL并执行一些增删改查
一.首先先创建一个C#的控制台应用 二.然后添加上必要的命名空间 using System;using System.Collections.Generic;using MySql.Data.MySq ...
- tp框架的增删改查
首先,我们来看一下tp框架里面的查询方法: 查询有很多种,代码如下: <?php namespace Admin\Controller; use Think\Controller; class ...
- nodejs+easyui(抽奖活动后台)增删改查
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfAAAAJACAIAAAD97KNZAAAgAElEQVR4nO2daXxb5Z2o7w+dO1/ufL ...
- 使用EF自带的EntityState枚举和自定义枚举实现单个和多个实体的增删改查
本文目录 使用EntityState枚举实现单个实体的增/删/改 增加:DbSet.Add = > EntityState.Added 标记实体为未改变:EntityState.Unchange ...
随机推荐
- Zookeeper选举算法原理
Zookeeper选举算法原理 Leader选举 Leader选举是保证分布式数据一致性的关键所在.当Zookeeper集群中的一台服务器出现以下两种情况之一时,需要进入Leader选举. (1) 服 ...
- springmvc的json数据交互
准备 @RequestBody 作用: @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json ...
- MySQL事务实现原理
MySQL事务隔离级别的实现原理 知识储备 只有InnoDB支持事务,所以这里说的事务隔离级别是指InnoDB下的事务隔离级别 隔离级别 读未提交:一个事务可以读取到另一个事务未提交的修改.这会带来脏 ...
- Atom编辑器汉化
Atom编辑器汉化成中文版 其他分享 7个月前 (04-04) 426浏览 0评论 Atom 是 Github 专门为程序员推出的一个跨平台文本编辑器.小松今天看到了这个编辑器,而且感觉不错,推荐一下 ...
- Golang教程:Map
什么是 map? Map 是 Go 中的内置类型,它将键与值绑定到一起.可以通过键获取相应的值. 如何创建 map? 可以通过将键和值的类型传递给内置函数 make 来创建一个 map.语法为:mak ...
- Golang教程:类型
下面是 Go 支持的基本类型: bool Numeric Types int8, int16, int32, int64, int uint8,uint16,uin32,uint64, uint f ...
- python-爬虫之re模块
re模块中常用功能函数 1.compile() 编译正则表达式模式,返回一个对象的模式.(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率.) 格式: re.compile(pat ...
- redis(3)发布订阅
一.发布/订阅模式 在软件工程里面,发布/订阅是一种消息模式,这种模式旨在将消息发送者和消息接收者解耦.发送者不需要关心将消息发送给谁,接收者也不需要知道消息的发送者是谁.发送者将消息发布以后就结束动 ...
- JS埋点 小结
今天在看<大型网站性能监测.分析与优化>一书,提到性能监测方式,才知道有这个名词 “JS埋点”. 大概作用:通过在web页面中,添加js脚本,实现对页面性能监测(如加载时间.服务器响应时间 ...
- Vue中的静态资源管理(src下的assets和static文件夹的区别)
### 你可能注意到了我们的静态资源共有两个目录src/assets和static/,你们它们之间有怎样的区别呢? 资源打包 为了回答这个问题,我们需要了解webpack是如何处理静态资源的. 在所有 ...