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/ 系列目录: ...
随机推荐
- Swift自适应布局(Adaptive Layout)教程(一)
通用的stroyboard文件是通向自适应布局光明大道的第一步.在一个storyboard文件中适配iPad和iPhone的布局在iOS8中已不再是梦想.我们不必再为不同尺寸的Apple移动设备创建不 ...
- eclipse中安装thymeleaf插件完成thymeleaf模板中自动代码提示功能
插件地址:https://github.com/thymeleaf/thymeleaf-extras-eclipse-plugin 页面有介绍如何使用:
- linux单机限速工具
wondershaper是国外人开发的一款在Linux内核下基于TC工具的对整块网卡的限度工具. http://lartc.org/wondershaper/ 安装wondershaper: [roo ...
- Win10 设备补丁更新
用户对客户端设备补丁更新保持怀疑态度,因为他们担心他们的计算机会在未经许可的情况下突然自己重启,丢失数据.虽然,您可以在更新后推迟重新启动并安排选择的时间,具体取决于更新Windows在未经您许可的情 ...
- struts2.3.4.1转换成eclipse项目的过程
1.在本地安装配置maven. 1.1.从maven官网下载,官网地址:http://maven.apache.org/download.cgi 1.2.配置maven环境变量 例如,我的 ...
- 3.tomcat
1.进入网站http://www.apache.org 2.选择 3.关闭防火墙才可以让别人访问自己
- vuejs作用域插槽
作用域插槽 <div id='root'> <child> <template slot-scope='props'> <h1>{{props.item ...
- win10启动项添加方法
1.添加或删除启动文件夹下的快捷方式实现开机自启动 我们可以直接将应用软件的快捷方式拖到启动文件夹里,下次开机时便会自动运行这些软件. 不需要开机启动某些软件了就将启动文件夹里的该软件的快捷方式删除掉 ...
- Jmeter启动错误
错误一 1 apache-jmeter-2.13\bin>jmeter 'findstr' 不是内部或外部命令,也不是可运行的程序 或批处理文件. Not able to find Java e ...
- 2017.11.16 JavaWeb-------第八章 EL、JSTL、Ajax技术
第八章 EL.JSTL.Ajax技术 ~~ EL (expression language) 是表达式语言 ~~ JSTL(JSP Standard Tag Library) 是开源的JSP标准标签库 ...