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基础增删查改、事务和存储过程的更多相关文章

  1. Django笔记&教程 5-1 基础增删查改

    Django 自学笔记兼学习教程第5章第1节--基础增删查改 点击查看教程总目录 第四章介绍了模型类models.Model和创建模型,相当于介绍了数据库表和如何创建数据库表. 这一章将介绍如何使用模 ...

  2. hibernate基础增删查改简单实例

    hibernate 基础理论知识网上很多,可以百度和google.这里不做多的介绍,以一个User表来开展例子 建一个web-project 我这里用了junit单元测试环境来进行增删查改的测试,别的 ...

  3. EF增删查改加执行存储过程和sql语句,多种方法汇总

    ActionUrl c = new ActionUrl() { ActionName="test", RequestUrl="/123/123", SubTim ...

  4. mysql入门基础增删查改

    数据查询语法(DQL) DQL就是数据查询语言,数据库执行DQL语句不会对数据进行改变,而是让数据库发送结果集给客户端. 语法: SELECT selection_list /*要查询的列名称*/ F ...

  5. Yii框架基础增删查改

    返回一条数据 Country::find()->one(); 返回所有数据 Country::find()->all(); 返回记录的数量 $country =Country::find( ...

  6. 使用EntityFramework6完成增删查改和事务

    使用EntityFramework6完成增删查改和事务 上一节我们已经学习了如何使用EF连接数据库,并简单演示了一下如何使用EF6对数据库进行操作,这一节我来详细讲解一下. 使用EF对数据库进行操作, ...

  7. 使用EntityFramework6完成增删查改CRUD和事务

    使用EntityFramework6完成增删查改和事务 上一节我们已经学习了如何使用EF连接MySQL数据库,并简单演示了一下如何使用EF6对数据库进行操作,这一节我来详细讲解一下. 使用EF对数据库 ...

  8. Mybatis基础配置及增删查改操作

    一.简介 平时我们都用JDBC访问数据库,除了需要自己写SQL之外,还必须操作Connection, Statement, ResultSet 这些其实只是手段的辅助类. 不仅如此,访问不同的表,还会 ...

  9. 4.在MVC中使用仓储模式进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...

随机推荐

  1. 跨平台移动开发phonegap/cordova 3.3全系列教程-helloworld

    1.    建立专案(cordova) 打开cmd命令行 cordova create ACESMobile aces.mobile ACES cd aces mobile 如图 2.    安装插件 ...

  2. python字符转码

    字符的编码与转码 demo UTF-8 转GBK python2.7 默认编码ASCII 没有转Unicode 直接转GBK 1 .系统的默认编码是ASCII , 程序的指定编码是UTF-8,在enc ...

  3. Struts2 简介及学习方法介绍

    Struts2 =  webwork + struts1.x 尊重学习规律的操作 学习上痛苦的根源之一是只能走的时候逼我来跑 不是说深入的内容就不讲了,而是放到合适的时候讲 一段时间可以,长了集中不了 ...

  4. Zamplus 晶赞天机

    类型: 定制服务 软件包: car/vehicle integrated industry solution collateral tourism 联系服务商 产品详情 解决方案 概要 DMP:通常称 ...

  5. Java中的字符集

    Java中的字符集 1.字符集概述 字符集是各国家文字与字符编码对照表.字符可以看成是计算机中展示的图案效果,每个字符集都对每一种图案进行编码,有着一对一的对应关系.因此进行字符输出时,都需要指定使用 ...

  6. 线程属性总结 线程的api属性

    http://blog.csdn.net/zsf8701/article/details/7842392 //线程属性结构如下:typedef struct{ int etachstate; //线程 ...

  7. 2019.03.09 ZJOI2019模拟赛 解题报告

    得分: \(20+0+40=60\)(\(T1\)大暴力,\(T2\)分类讨论写挂,\(T3\)分类讨论\(40\)分) \(T1\):天空碎片 一道神仙数学题,貌似需要两次使用中国剩余定理. 反正不 ...

  8. 2017.11.24 算法分析与设计------Gay格雷码

    1. 格雷码问题: 对于给定的正整数n,格雷码为满足如下条件的一个编码序列: (1) 序列由2n个编码组成,每个编码都是长度为n的二进制位串. (2) 序列中无相同的编码. (3) 序列中位置相邻的两 ...

  9. vim 中的":wq"和":x"的区别

    ":x" 和 ":wq" 的区别如下:(1) :wq 强制性写入文件并退出(存盘并退出 write and quite).即使文件没有被修改也强制写入,并更新文 ...

  10. Mybatis之批量更新操作

    更新单条记录 UPDATE course SET name = 'course1' WHERE id = 'id1'; 更新多条记录的同一个字段为同一个值 UPDATE course SET name ...