Dapper基础增删查改、事务和存储过程
1.前言
Dapper是一个轻量级的orm框架,上手也非常的简单,它可以实体映射,所以先准备实体如下:
public class Couser
{
public int id { get; set; }
public string courseName { get; set; }
}
public partial class Score
{
public int id { get; set; }
public int score { get; set; }
public int courseId { get; set; }
public int studentId { get; set; }
public Student student { get; set; }
public Couser couser { get; set; }
}
public partial class Student
{
public int id { get; set; }
public string name { get; set; }
public int sex { get; set; }
public string tel { get; set; }
public string other { get; set; }
public Score scoreModel { get; set; }
}
2.查询
1.QueryFist查询单个实体
  Dapper会自动匹配class的属性和sql查询出来的字段进行数据的组装,这里的属性可以不是表中存在的而是自己定义添加的。但是不会对class中的类属性里的属性进行赋值,比如Student里面有个public Score scoreModel { get; set; }就不会对Score这个类里面的属性进行赋值。反而会对scoreModel进行赋值,加入sql语句返回了一个int类型的scoreModel字段的数据,但是和scoreModel的类型不匹配无法转换就会报错。
public Student QueryFirst_1()
{
using (IDbConnection conn = new SqlConnection(sqlconnection))
{
return Dapper.SqlMapper.QueryFirstOrDefault<Student>(conn, "select a.*,b.score as other,b.* from Student a left join Score b on a.id = b.studentId where a.id=@id ", new { id = });
//return Dapper.SqlMapper.QueryFirst<Student>(conn, "select a.*,b.score as other from Student a left join Score b on a.id = b.studentId ");
//return Dapper.SqlMapper.QueryFirst<Student>(conn, "select * from Student where id=123");
}
}
其实CommandDefinition传入的效果和直接传递参数效果相同,只是把原先要传递的参数先传到CommandDefinition中
public Student QueryFist_2()
{
using (IDbConnection conn = new SqlConnection(sqlconnection))
{
string strsql = "select a.*,b.score as other from Student a left join Score b on a.id = b.studentId where a.id=@id";
CommandDefinition command = new CommandDefinition(strsql, new { id = });
return Dapper.SqlMapper.QueryFirstOrDefault<Student>(conn, command);
}
}
2.QuerySingle查询单个实体
  和QueryFist一样是查询单条数据,差别是QueryFist在返回多条数据的情况下会默认获取第一条,QuerySingle返回多条数据的话就会报错
public Student QuerySingle_1()
{
using (IDbConnection conn = new SqlConnection(sqlconnection))
{
return Dapper.SqlMapper.QuerySingleOrDefault<Student>(conn, "select a.*,b.score as other from Student a left join Score b on a.id = b.studentId where a.id=@id ", new { id = });
}
}
3.Query查询多条数据,单表查询
public List<Student> Query_1()
{
using (IDbConnection conn = new SqlConnection(sqlconnection))
{
return Dapper.SqlMapper.Query<Student>(conn, "select a.*,b.score as other from Student a left join Score b on a.id = b.studentId where a.id=@id ", new { id = }).ToList<Student>();
}
}
4.Query查询多条数据,多表的映射
  splitOn默认值是id,它是用来切割将不同的类的属性匹配到相应的类中
public List<Student> Query_2()
{
using (IDbConnection conn = new SqlConnection(sqlconnection))
{
return Dapper.SqlMapper.Query<Student,Score,Student>(conn, "select a.*,b.* from Student a left join Score b on a.id = b.studentId where a.id=@id ",
(Student, Score) => { Student.scoreModel = Score; return Student; },
new { id = }, //参数
null, //事务
true, //是否缓存
"id",
null,//超时时间
null//执行类型,如存储过程等
).ToList<Student>();
}
}
3.增删改和事务
增删改的操作其实是差不多的,所以用一下代码为实例:
public void Add()
{
using (IDbConnection conn = new SqlConnection(sqlconnection))
{
string inesrtSql = "insert into Student(name,sex,tel) values (@name,@sex,@tel)";
Student student_1 = new Student();
student_1.name = "名字哦";
student_1.sex = ;
student_1.tel = "";
Student student_2 = new Student();
student_2.name = "名字哦1";
student_2.sex = ;
student_2.tel = "";
List<Student> list = new List<Student>();
list.Add(student_1);
list.Add(student_2);
conn.Open();//使用事务前必须打开链接
IDbTransaction tran = conn.BeginTransaction();
try
{
if (Dapper.SqlMapper.Execute(conn, inesrtSql, list, tran) > )//多条插入,不使用事务的话,执行错误会导致脏数据
{
tran.Commit();
//成功
}
else
{
//失败
}
}
catch (Exception ex)
{
tran.Rollback();
}
//if (Dapper.SqlMapper.Execute(conn, inesrtSql, student_1) > 0)//单条插入
//{
// //成功
//}
//else
//{
// //失败
//}
}
}
4.存储过程和函数
简单实例如下:
public void StoredProcedureAndFun()
{
using(IDbConnection conn = new SqlConnection(sqlconnection))
{
var para = new DynamicParameters();
para.Add("@id", );
para.Add("@res", , DbType.Int32, ParameterDirection.ReturnValue);//定义返回值
var res1 = conn.Query("storedProcedure", para, null, true, null, CommandType.StoredProcedure).FirstOrDefault(); //只要using Dapper就可以直接用conn.Query()的形式
para.Get<int>("@res");//获取返回值
}
}
Dapper基础增删查改、事务和存储过程的更多相关文章
- Django笔记&教程 5-1 基础增删查改
		
Django 自学笔记兼学习教程第5章第1节--基础增删查改 点击查看教程总目录 第四章介绍了模型类models.Model和创建模型,相当于介绍了数据库表和如何创建数据库表. 这一章将介绍如何使用模 ...
 - hibernate基础增删查改简单实例
		
hibernate 基础理论知识网上很多,可以百度和google.这里不做多的介绍,以一个User表来开展例子 建一个web-project 我这里用了junit单元测试环境来进行增删查改的测试,别的 ...
 - EF增删查改加执行存储过程和sql语句,多种方法汇总
		
ActionUrl c = new ActionUrl() { ActionName="test", RequestUrl="/123/123", SubTim ...
 - mysql入门基础增删查改
		
数据查询语法(DQL) DQL就是数据查询语言,数据库执行DQL语句不会对数据进行改变,而是让数据库发送结果集给客户端. 语法: SELECT selection_list /*要查询的列名称*/ F ...
 - Yii框架基础增删查改
		
返回一条数据 Country::find()->one(); 返回所有数据 Country::find()->all(); 返回记录的数量 $country =Country::find( ...
 - 使用EntityFramework6完成增删查改和事务
		
使用EntityFramework6完成增删查改和事务 上一节我们已经学习了如何使用EF连接数据库,并简单演示了一下如何使用EF6对数据库进行操作,这一节我来详细讲解一下. 使用EF对数据库进行操作, ...
 - 使用EntityFramework6完成增删查改CRUD和事务
		
使用EntityFramework6完成增删查改和事务 上一节我们已经学习了如何使用EF连接MySQL数据库,并简单演示了一下如何使用EF6对数据库进行操作,这一节我来详细讲解一下. 使用EF对数据库 ...
 - Mybatis基础配置及增删查改操作
		
一.简介 平时我们都用JDBC访问数据库,除了需要自己写SQL之外,还必须操作Connection, Statement, ResultSet 这些其实只是手段的辅助类. 不仅如此,访问不同的表,还会 ...
 - 4.在MVC中使用仓储模式进行增删查改
		
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...
 
随机推荐
- Azure进阶攻略 | 下载还是在浏览器直接打开,MIME说了算!
			
多年来,从一开始的网络菜鸟发展成 Azure 云专家,想必你一定学到了很多知识.不知道在这个过程中你自己是否遇到过,或者被人问到过类似下面这样的问题: 同样是直接点击网页上提供的 .mp4 视频文件链 ...
 - 开源时序服务器influxdb使用
			
文档 https://influxdb.com/docs/v0.9/introduction/overview.html 配置文件 /etc/opt/influxdb/influxdb.conf re ...
 - bootstrap文件上传fileupload插件
			
Bootstrap FileInput中文API整理:https://blog.csdn.net/u012526194/article/details/69937741 SpringMVC + boo ...
 - COGS 182. [USACO Jan07] 均衡队形
			
★★ 输入文件:lineup.in 输出文件:lineup.out 简单对比时间限制:4 s 内存限制:128 MB 题目描述 农夫约翰的 N (1 ≤ N ≤ 50,000) 头奶牛 ...
 - My First Blog in Cnblogs
			
终于打算从csdn搬到博客园了 虽然在csdn只写过三篇文章,不过打算写第四篇的时候发现原先的三篇都消失了.联系客服最终还是找回了,不过对于csdn神奇的管理方式还是不放心,也没在csdn上再写过文章 ...
 - 【LOJ6045】「雅礼集训 2017 Day8」价(网络流)
			
点此看题面 大致题意: 有\(n\)种药,每种药有一个权值,且使用了若干种药材.让你选择若干种药,使得药的数量与所使用的药材并集大小相等,求最小权值总和. 网络流 \(hl666\):这种数据范围,一 ...
 - 解决Gearman 报sqlite3错误
			
删除了系统原带的sqlite3 ,到官网上下一个源码,重新编译安装sqlite3. 如:把sqlite3安装到 /usr/local/sqlite3tar zxf sqlite3.xxxx.tar.g ...
 - 线程 task pritce
			
1.使用task类创建并执行简单任务: 使用task的构造函数来创建 任务,并调用start方法来启动任务,执行异步操作 aitAll用于等待提供的所有 System.Threading.Tasks. ...
 - [USACO07FEB]银牛派对Silver Cow Party---最短路模板题
			
银牛排队 对于我这种蒟蒻来说,还是不要跑一次单元最短路.跑两次好写呀(- ̄▽ ̄)- 而题目中是有向图.如果如果按照题意进行最短路的话.就会出现一个单终点最短路和一个单起点最短路 对于单起点自然就是套模 ...
 - java 基础词汇 必须 第九天
			
Collection 集合 List 列表集合 Set 不重复集合 Linked 链表 Vector 线程安全集合 Hash 哈希值 tree 树型结构 Map 键值对集合 add 增加 remove ...