使用轻量级ORM 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层就可以使用实体对象传参 或者作为返回值
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 = ;
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 = ;
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 = ;
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 = ;
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 = ;
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 = ;
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 = , B = "b"} // A will be mapped to the param @A, B to the param @B
看到Dapper那么特性,觉得使用Dapper非常方便,使用也非常方便,扩展性也非常高。 当我用Dapper写一个demo给项目经理看的时候,项目经理就同意使用
Dapper 作为ORM 进行数据访问层的开发。从此就爱上了Dapper。
希望这篇文章给你带来对Dapper清晰的了解。同时如果这文章给你到来了帮助,也别忘了帮忙推荐。
使用轻量级ORM Dapper进行增删改查的更多相关文章
- Django项目的创建与介绍.应用的创建与介绍.启动项目.pycharm创建启动项目.生命周期.三件套.静态文件.请求及数据.配置Mysql完成数据迁移.单表ORM记录的增删改查
一.Django项目的创建与介绍 ''' 安装Django #在cmd中输入pip3 #出现这个错误Fatal error in launcher: Unable to create process ...
- [Django框架 - 静态文件配置、request对象方法初识、 pycharm链接数据库、ORM实操增删改查、django请求生命周期]
[Django框架 - 静态文件配置.request对象方法初识. pycharm链接数据库.ORM实操增删改查.django请求生命周期] 我们将html文件默认都放在templates文件夹下 将 ...
- Dapper进行增删改查 z
http://www.cnblogs.com/huangkaiyan10/p/4640548.html 项目背景 前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET ...
- Dapper.Contrib——更加优雅地使用Dapper进行增删改查
简介 Dapper是介于Entity framework与ADO的折中选择.既满足手写查询的高性能需求,又简化了数据库对象映射为内存对象的繁杂工作.Dapper.Contrib是对Dapper的进一步 ...
- django -- ORM实现作者增删改查
前戏 前面我们已经实现了出版社的增删改查,书的增删改查,书和出版社的对应关系.现在来写一下作者的增删改查和书的对应关系,那书和作者有什么关系呢?一个作者可以写多本书,一本书可以有多个作者,所以书和作者 ...
- django -- ORM实现图书增删改查
表结构设计 上篇我们实现了出版社的增删改查,出版社数据表有两个字段id和name,那图书的表结构怎么设计呢?图书也要有一个主键id,还要有一个名称title,是哪个出版社的,要有个字段press和Pr ...
- django -- ORM实现出版社增删改查
前戏 我们来完成一个图书管理系统的增删改查 表结构设计 1. 出版社 id name 2. 作者 id name 3. 书 id title 出版社_id 4. 作者_书_关系表 id 书 ...
- ORM多表增删改查
一 创建多表 在models.py里创建4张表:Author(作者).AuthorDetail(作者详细信息).Publish(出版社).Book(书) 四张表关系为: (1)首先创建一对一关系.On ...
- ORM数据库的增删改查
数据库可视化工具: https://sqlitestudio.pl/index.rvt from app01 import models def orm(request): #增加数据 # 方法1: ...
随机推荐
- 使用C# WinForm窗体制作经理评分项目 ——S2 2.2
在窗口加载时初始化三个员工对象 用数组存放 这是员工类的大致字段和属性. 在FrmMain中给对象数组附初值 以上 FrmMain中用一个ListView控件展示员工信息,通过以上代码将对象数组中的内 ...
- Java制作证书的工具keytool用法总结
一.keytool的概念 keytool 是个密钥和证书管理工具.它使用户能够管理自己的公钥/私钥对及相关证书,用于(通过数字签名)自我认证(用户向别的用户/服务认证自己)或数据完整性以及认证服务.在 ...
- android项目中使用开源数据库litepal
下载地址 https://github.com/LitePalFramework/LitePal 参考文档 http://blog.csdn.net/guolin_blog/article/detai ...
- css加阴影
box-shadow: 1px 1px 3px 1px rgba(0,0,0,0.1); -webkit-box-shadow: 1px 1px 3px 1px rgba(0,0,0,0.1); -m ...
- HDU 1540 Tunnel Warfare(线段树+区间合并)
http://acm.hdu.edu.cn/showproblem.php?pid=1540 题目大意:抗日战争期间进行地道战,存在n个村庄用地道连接,输入D表示破坏某个村庄(摧毁与其相连的地道, 包 ...
- BIEE 11g 安装
1.安装oracle 创建字符集为AL32UTF8的实力MERIT sys密码merit 创建biee用户 create tablespace biee datafile 'D:\ORADATA\M ...
- 自动化测试工具QTP和SilkTest横向PK(转)
转自:http://www.uml.org.cn/Test/201405212.asp?artid=1686 众所周知,自动化测试工具曾几何时三足鼎立,Mercury QTP/WinRunner系.I ...
- 使用jquery的trigger方法优化页面代码
我们做页面级联的时候经常会用到ajax处理数据,会为下拉菜单编写change事件. //城市和区域联动 $("#City").change(function () { var ci ...
- 多线程JAVA篇(一)
解析AsyncTask源码之前,首先讲述与之相关的Java线程知识: 知识点清单 1.Thread类 2.Runnable接口 3.Callable接口 4.synchronized关键字 5.vol ...
- C++Builder 中 Enter键或者Tab键无效
VC++中或者C++Builder中 当回车键不能换行时应该就是因为自己不小心按到了键盘上的insert键,要想恢复只需要再按一下就可以了. 小经验