轻量ORM-SqlRepoEx (十四)最佳实践之Dapper(1)
简介:SqlRepoEx是 .Net平台下兼容.NET Standard 2.0人一个轻型的ORM。解决了Lambda转Sql语句这一难题,SqlRepoEx使用的是Lambda表达式,所以,对c#程序员来说,是非常简单的,其语法特点与Linq to Sql极为相似。不仅实现了完整的Select、Insert、Update、Delete等语句解析器,同时,也实现了Select、where、order by等子句,这些语句与子句均支持导出SQL语句,使得拼接复杂场景SQL语句变得轻松,SqlRepoEx很快其原生数据访问与Dapper不相上下,SqlRepoEx本身支持Sql Server与MySql方言,同时通过SqlRepoEx.Normal支持非方言SQL。SqlRepoEx没侵入性,仅通过简单的几个特性,就能让类与数据库关联起来;
*本系列以静态工厂为例;
*数据来源于Northwind数据库;
*完整的代码见 SqlRepoEx2.2.1 GitHub示例 SqlRepoEx2.2.1 码云示例
一、IDbConnection
可通过下列两种方式获取
1、工厂获取
private static IDbConnection dbConnection = MsSqlRepoFactory.DbConnection;
2、数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
IDbConnection dbConnection = repository.DbConnection;
二、 SQL语句中 @ 参数的生成和定义
1、SqlRepoEx的Insert、Updata 增加了ParamSql()方法获取 @ 参数 语句;
2、对于Where条件语句中,如要生成 @ 参数 语句 只需要在表达式中 .Where(p => p.ProductID == p.ProductID);右侧表达式中使用类型属性表达式即可。
3、关于数据字段与属性联,将在下篇中介绍
三、 简单查询
public static void QueryOnly()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
//查询
var result = repository.Query().Top(10);
Console.WriteLine(result.Sql());
// 通过 Dapper 获取数据
IEnumerable<AzProducts> azProducts = dbConnection.Query<AzProducts>(result.Sql());
// 显示结果(只取两列,仅为显示目的)
foreach (var item in azProducts)
{
Console.WriteLine($"{item.ProductID}\t{item.ProductName2}");
}
}
此方法生成的 SQL
SELECT TOP (10) [dbo].[Products].[ProductID]
, [dbo].[Products].[ProductName] as [ProductName2]
, [dbo].[Products].[SupplierID]
, [dbo].[Products].[CategoryID]
, [dbo].[Products].[QuantityPerUnit]
, [dbo].[Products].[UnitPrice]
, [dbo].[Products].[UnitsInStock]
, [dbo].[Products].[UnitsOnOrder]
, [dbo].[Products].[ReorderLevel]
, [dbo].[Products].[Discontinued]
FROM [dbo].[Products];
此方法生成的结果
1 Chai
2 Chang
3 Aniseed Syrup
4 Chef Anton's Cajun Seasoning
5 Chef Anton's Gumbo Mix
6 Grandma's Boysenberry Spread
7 Uncle Bob's Organic Dried Pears
8 Northwoods Cranberry Sauce
9 Mishi Kobe Niku
10 Ikura
四、InnerJoin 查询
* LeftOuterJoin、RightOuterJoin与此例相似
public static void DoInnerJoin()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
// 构建查询语句,相较而言,语法更接近于SQL,与Linq是有很大区别的
var result = repository.Query()
.InnerJoin<AzSuppliers>()
.On<AzSuppliers>((l, r) => l.SupplierID == r.SupplierID, r => r.CompanyName)
.Top(10);
Console.WriteLine(result.Sql());
Console.WriteLine();
// 通过 Dapper 获取数据
IEnumerable<AzProducts> azProducts = dbConnection.Query<AzProducts>(result.Sql());
foreach (var item in azProducts)
{
Console.WriteLine($"{item.ProductID}\t{item.ProductName2}\t{item.Supplier}");
}
}
此方法生成的 SQL
SELECT TOP (10) [dbo].[Products].[ProductID]
, [dbo].[Products].[ProductName] as [ProductName2]
, [dbo].[Products].[SupplierID]
, [dbo].[Products].[CategoryID]
, [dbo].[Products].[QuantityPerUnit]
, [dbo].[Products].[UnitPrice]
, [dbo].[Products].[UnitsInStock]
, [dbo].[Products].[UnitsOnOrder]
, [dbo].[Products].[ReorderLevel]
, [dbo].[Products].[Discontinued]
, [dbo].[Suppliers].[CompanyName] as [Supplier]
FROM [dbo].[Products]
INNER JOIN [dbo].[Suppliers]
ON [dbo].[Products].[SupplierID] = [dbo].[Suppliers].[SupplierID];
此方法生成的结果
1 Chai Exotic Liquids
2 Chang Exotic Liquids
3 Aniseed Syrup Exotic Liquids
4 Chef Anton's Cajun Seasoning New Orleans Cajun Delights
5 Chef Anton's Gumbo Mix New Orleans Cajun Delights
6 Grandma's Boysenberry Spread Grandma Kelly's Homestead
7 Uncle Bob's Organic Dried Pears Grandma Kelly's Homestead
8 Northwoods Cranberry Sauce Grandma Kelly's Homestead
9 Mishi Kobe Niku Tokyo Traders
10 Ikura Tokyo Traders
五、条件查询
public static void QueryWhere()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
var result = repository.Query()
.Where(p => p.ProductName2.Contains("t") && p.ProductID < 100)
.Top(10);
Console.WriteLine(result.Sql());
Console.WriteLine();
// 通过 Dapper 获取数据
IEnumerable<AzProducts> azProducts = dbConnection.Query<AzProducts>(result.Sql());
foreach (var item in azProducts)
{
Console.WriteLine($"{item.ProductID}\t{item.ProductName2}");
}
}
此方法生成的 SQL
SELECT TOP (10) [dbo].[Products].[ProductID]
, [dbo].[Products].[ProductName] as [ProductName2]
, [dbo].[Products].[SupplierID]
, [dbo].[Products].[CategoryID]
, [dbo].[Products].[QuantityPerUnit]
, [dbo].[Products].[UnitPrice]
, [dbo].[Products].[UnitsInStock]
, [dbo].[Products].[UnitsOnOrder]
, [dbo].[Products].[ReorderLevel]
, [dbo].[Products].[Discontinued]
FROM [dbo].[Products]
WHERE ((([dbo].[Products].[ProductName] LIKE '%t%') and ([dbo].[Products].[ProductID] < 100)));
此方法生成的结果
4 Chef Anton's Cajun Seasoning
5 Chef Anton's Gumbo Mix
8 Northwoods Cranberry Sauce
12 Queso Manchego La Pastora
14 Tofu
17 Alice Mutton
18 Carnarvon Tigers
19 Teatime Chocolate Biscuits
22 Gustaf's Kn?ckebr?d
23 Tunnbr?d
六、Union
public static void QueryUnion()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzCustomers>();
// 此语句不会参与数据查询,只是作为Union的包裹
// 如果此语句本身也是数据查询,请增加到new List<UnionSql>中
var result = repository.Query()
.Select(c => c.CustomerID, c => c.CompanyName);
var result01 = repository.Query()
.Select(c => c.CustomerID, c => c.CompanyName)
.Where(c => c.CustomerID == "ANATR");
var result02 = repository.Query()
.Select(c => c.CustomerID, c => c.CompanyName)
.Where(c => c.CustomerID == "FRANK");
var result03 = repository.Query()
.Select(c => c.CustomerID, c => c.CompanyName)
.Where(c => c.CustomerID == "TRADH");
var resultAllSql = result.UnionSql(new List<UnionSql> {
UnionSql.New( result01,UnionType.Union ),
UnionSql.New( result02,UnionType.Union ),
UnionSql.New( result03,UnionType.Union ), });
Console.WriteLine(resultAllSql);
Console.WriteLine();
// 通过 Dapper 获取数据
IEnumerable<AzCustomers> azCustomers = dbConnection.Query<AzCustomers>(resultAllSql);
foreach (var item in azCustomers)
{
Console.WriteLine($"{item.CustomerID}\t{item.CompanyName}");
}
}
此方法生成的 SQL
SELECT [_this_is_union].[CustomerID]
, [_this_is_union].[CompanyName]
FROM ( SELECT [dbo].[Customers].[CustomerID]
, [dbo].[Customers].[CompanyName]
FROM [dbo].[Customers]
WHERE (([dbo].[Customers].[CustomerID] = 'ANATR'))
UNION
SELECT [dbo].[Customers].[CustomerID]
, [dbo].[Customers].[CompanyName]
FROM [dbo].[Customers]
WHERE (([dbo].[Customers].[CustomerID] = 'FRANK'))
UNION
SELECT [dbo].[Customers].[CustomerID]
, [dbo].[Customers].[CompanyName]
FROM [dbo].[Customers]
WHERE (([dbo].[Customers].[CustomerID] = 'TRADH')) )
AS _this_is_union
此方法生成的结果
ANATR Ana Trujillo Emparedados y helados
FRANK Frankenversand
TRADH Tradi??o Hipermercados
七、增加(使用实例)
public static void DoInsertEntityParam()
{
var repository = MsSqlRepoFactory.Create<AzProducts>();
AzProducts azProduct = new AzProducts { ProductName2 = "testvalue" };
var resultinsert = repository
.Insert();
// 使用ParamSql()方法获取 @ 参数SQL语句
Console.WriteLine(resultinsert.ParamSql());
Console.WriteLine();
// 需返回自增字段,所以用Query
IEnumerable<AzProducts> azProducts = dbConnection.Query<AzProducts>(resultinsert.ParamSql(), azProduct);
foreach (var item in azProducts)
{
Console.WriteLine($"{item.ProductID}\t{item.ProductName2}");
}
}
此方法生成的 SQL
INSERT [dbo].[Products]([ProductName],[SupplierID],[CategoryID],[QuantityPerUnit],[UnitPrice],[UnitsInStock],[UnitsOnOrder],[ReorderLevel],[Discontinued])
VALUES(@ProductName2,@SupplierID,@CategoryID,@QuantityPerUnit,@UnitPrice,@UnitsInStock,@UnitsOnOrder,@ReorderLevel,@Discontinued);
SELECT [ProductID],[ProductName] as ProductName2,[SupplierID],[CategoryID],[QuantityPerUnit],[UnitPrice],[UnitsInStock],[UnitsOnOrder],[ReorderLevel],[Discontinued]
FROM [dbo].[Products]
WHERE [ProductID] = SCOPE_IDENTITY();
此方法生成的结果
96 testvalue
八、批增加(使用选择)
public static void DoInsertEntityParamBatch()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
// 设置要批处理的数据
List<AzProducts> azProductList = new List<AzProducts>{
new AzProducts { ProductName2 = "testvalue1" ,CategoryID=1,UnitPrice=123},
new AzProducts { ProductName2 = "testvalue2" ,CategoryID=1,UnitPrice=123},
new AzProducts { ProductName2 = "testvalue3" ,CategoryID=1,UnitPrice=123},
new AzProducts { ProductName2 = "testvalue4" ,CategoryID=1,UnitPrice=123 },
new AzProducts { ProductName2 = "testvalue5" ,CategoryID=1,UnitPrice=123},
new AzProducts { ProductName2 = "testvalue6" ,CategoryID=1,UnitPrice=123},
};
// 使用选择增加
var resultinsert = repository
.Insert().ParamWith(c => c.ProductName2, c => c.UnitPrice, c => c.CategoryID);
Console.WriteLine(resultinsert.ParamSql());
Console.WriteLine();
// 通过 Dapper 批处理
dbConnection.Execute(resultinsert.ParamSql(), azProductList);
}
此方法生成的 SQL
INSERT [dbo].[Products]([ProductName],[UnitPrice],[CategoryID])
VALUES(@ProductName2,@UnitPrice,@CategoryID);
SELECT [ProductName] as ProductName2,[UnitPrice],[CategoryID],[ProductID]
FROM [dbo].[Products]
WHERE [ProductID] = SCOPE_IDENTITY();
九、更新
public static void DoUpdateEntityParam()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
// 构建更新语句
var resultUpdate = repository
.Update()
.ParamSet(p => p.ProductName2, p => p.CategoryID)
// Where 中使用下列格式语句,可生成带 @ 的参数
.Where(p => p.ProductID == p.ProductID);
Console.WriteLine(resultUpdate.ParamSql());
Console.WriteLine();
// 需更新的数据
AzProducts products = new AzProducts() { ProductID = 84, ProductName2 = "testvalue100", CategoryID = 7 };
// 通过 Dapper 更新数据
int result = dbConnection.Execute(resultUpdate.ParamSql(), products);
Console.WriteLine($"{result}");
}
此方法生成的 SQL
UPDATE [dbo].[Products]
SET ProductName = @ProductName2, CategoryID = @CategoryID
WHERE (([dbo].[Products].[ProductID] = @ProductID));
十、删除
public static void DoDeleteEntity(bool go = false)
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
// 要删除的数据
AzProducts azProducts = new AzProducts { ProductName2 = "testvalue", ProductID = 81 };
// 构建删除,使用实例构建时,如果不设置 Where 语句
// SqlRepoEx 会以关键词来构建 Where 语句
var resultUpdate = repository.Delete().For(azProducts);
Console.WriteLine(resultUpdate.Sql());
Console.WriteLine();
// 通过 Dapper 删除数据
int result = dbConnection.Execute(resultUpdate.Sql());
Console.WriteLine($"{result}");
}
此方法生成的 SQL
DELETE [dbo].[Products]
WHERE (([dbo].[Products].[ProductID] = @ProductID));
十一、使用事务
public static void DoDeleteTransaction()
{
// 创建数据仓储
var repository = MsSqlRepoFactory.Create<AzProducts>();
// 构建删除,如果不是实例构建,用户必需自行指定删除条件
// Where 中使用下列格式语句,可生成带 @ 的参数
var resultUpdate = repository.Delete().Where(p => p.ProductID == p.ProductID);
// 要删除的数据集
List<AzProducts> azProductList = new List<AzProducts>
{
new AzProducts{ProductID=92},
new AzProducts{ProductID=93},
new AzProducts{ProductID=94},
new AzProducts{ProductID=91},
};
Console.WriteLine(resultUpdate.Sql());
Console.WriteLine();
// 使用事务控制
using (var transaction = dbConnection.BeginTransaction())
{
// 通过 Dapper 删除,同时指定了事务
dbConnection.Execute(resultUpdate.Sql(), azProductList, transaction: transaction);
// 仅为了演示,此处回滚事务,取消删除
// 如果相要提交事务,请将此处改为 transaction.Commit() 可看到删除效果
transaction.Rollback();
}
}
此方法生成的 SQL
DELETE [dbo].[Products]
WHERE (([dbo].[Products].[ProductID] = @ProductID));
轻量ORM-SqlRepoEx (十四)最佳实践之Dapper(1)的更多相关文章
- 轻量ORM-SqlRepoEx (十三)最佳实践
ORM-SqlRepoEx 是 .Net平台下兼容.NET Standard 2.0,一个实现以Lambda表达式转转换标准SQL语句,使用强类型操作数据的轻量级ORM工具,在减少魔法字串同时,通过灵 ...
- 轻量ORM-SqlRepoEx (十六)最佳实践之Dapper(2)
简介:SqlRepoEx是 .Net平台下兼容.NET Standard 2.0人一个轻型的ORM.解决了Lambda转Sql语句这一难题,SqlRepoEx使用的是Lambda表达式,所以,对c#程 ...
- 软件设计师【软件工程:软件开发模型、XP极限编程十二最佳实践】
一.软件开发模型 二.XP极限编程十二最佳实践
- Dapper.NET——轻量ORM
Dapper.NET使用 http://www.cnblogs.com/yankliu-vip/p/4182892.html 本文目录 Dapper.NET使用 1.为什么选择Dapper 2.以Da ...
- SqlSugar轻量ORM
蓝灯软件数据股份有限公司项目,代码开源. SqlSugar是一款轻量级的MSSQL ORM ,除了具有媲美ADO的性能外还具有和EF相似简单易用的语法. 学习列表 0.功能更新 1.SqlSuga ...
- 采用轻量ServiceMesh实现灰度发布的实践
软件总会有缺陷的,解决问题的同时往往会引入新的问题,关键是看这些问题是否在我们的控制范围内,“灰度发布”就是让问题受控的方法之一. 前言 我们的 CTO 经常说:“研发团队最首要的任务是提供稳定的服务 ...
- Dapper.NET—轻量ORM
Dapper.NET使用 本文目录 Dapper.NET使用 1.为什么选择Dapper 2.以Dapper(4.0)为例. 2.1 在数据库中建立几张表. 2.2实体类. 3.使用方法 3.1 一 ...
- [转] Jenkins Pipeline插件十大最佳实践
[From] http://blog.didispace.com/jenkins-pipeline-top-10-action/ Jenkins Pipeline 插件对于 Jenkins 用户来说可 ...
- 轻量ORM-SqlRepoEx (十五)最佳实践之数据映射(Map)
简介:SqlRepoEx是 .Net平台下兼容.NET Standard 2.0人一个轻型的ORM.解决了Lambda转Sql语句这一难题,SqlRepoEx使用的是Lambda表达式,所以,对c#程 ...
随机推荐
- 关于js的两个函数
注:这两个函数结合其他主要实现异步的默认checkbox选中和其他选中,从php页面穿过来已经选中的值,用jQuery 回绑:关键点在于$.each(),遍历,再用$.attr() 回绑:第二步关键点 ...
- win7 远程连接服务器出现身份验证错误,且找不到加密Oracle修正
用远程桌面连接登录服务器,结果,弹出一个错误的提示框:发生身份验证错误,要求的函数不受支持. 然后在网上找了相关的教程,基本上所有的方法都是如下所示: 策略路径:"计算机配置"-& ...
- Android链接蓝牙电子称
蓝牙一直是我内心屏蔽的一个模块哈哈哈哈!然而今天我不得不正视它了,我百度了看了好多因为需要设备匹配所以设备不在没办法测试,几天之后设备到了.因为没有接触过,看到返回的打印出来的菱形方块就以为是错了.于 ...
- maven-windows使用
目录 前言 安装 配置镜像 idea配置Maven 私服 安装到centos 访问 客户端配置私服 idea修改指定pom 项目发布到私服 jar包会自动从私服下载 从客户端导入第三方jar包 前言 ...
- MyCAT源码分析——分析环境部署
为了更好地了解mycat的原理,计划对mycat源码进行通读一遍,根据实际业务环境进行相关源码优化. 一.环境描述 操作系统:windows 10 x64 软件:jdk 1.7+ maven ...
- SQL捕捉blocking信息
场景: 客户抱怨数据库慢,但是回去看的时候,可能已经不慢了,为了查出当时到底是什么原因导致数据慢,制作了下面的存储过程,然后每隔3分钟运行一遍,把blocking信息插入一个数据库中. 主要就是查询s ...
- ORA-28001:口令已经失效
Oracle11G创建用户时缺省密码过期限制是180天(即6个月),如果超过180天用户密码未做修改则该用户无法登录. 查看密码的有效期设置,LIMIT字段是密码有效天数. select * from ...
- Java学习---连接数据库操作
Java连接Oracle数据库 package com.ftl.mysql; import java.sql.Connection; import java.sql.DriverManager; im ...
- CSMA/CD 3
一.二进制指数类型退避算法 (truncated binary exponential type) 发生碰撞的站在停止发送数据后,要推迟(退避)一个随机时间才能再发送数据. 目的:重传时再次发生碰撞的 ...
- windows下sqli-labs的搭建及学习(GET篇)
环境搭建: 源码下载地址:https://github.com/Audi-1/sqli-labs 需要搭建以下环境: apache+mysql+php Tomcat+mysql+java(部分关卡需要 ...