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. python+selenium第一个脚本

    #coding=utf-8from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport tim ...

  2. Azure降价辣么多,省下的预算该怎么花?

    那么 Azure 产品创新以及服务完善到底体现在何处呢?以下最新发布内容也许可以告诉你答案. ◆ ◆ ◆ Power BI Embedded 让应用中的数据更加生动 Microsoft Power B ...

  3. jmter安装配置

    一 JMeter 简介 JMeter 它是Apache组织的开放源代码项目,它是现在比较流行的功能和性能测试的工具.JMeter requires a fully compliant JVM 7 or ...

  4. *389. Find the Difference (string + map(26)) read problems carefully

    Given two strings s and t which consist of only lowercase letters. String t is generated by random s ...

  5. 是否应该提供一个dao.insertIgnoreNull ? (像updateIgnoreNull一样)

     是否应该提供一个dao.insertIgnoreNull ? (像updateIgnoreNull一样)  发布于 406天前  作者 SayingCode  153 次浏览  复制  上一个帖子  ...

  6. POJ-1469 COURSES---二分图最大匹配--匈牙利算法

    题目链接: https://vjudge.net/problem/POJ-1469 题目大意: 给你p门课程和n个学生,一个学生可以选0门,1门,或者多门课程,现在要求一个由p个学生组成的集合,满足下 ...

  7. Hive 配置显示表头和数据库信息

    在 conf/hive-site.xml 中添加如下配置 <property> <name>hive.cli.print.header</name> <val ...

  8. R 语言爬虫 之 cnblog博文爬取

    Cnbolg Crawl a). 加载用到的R包 ##library packages needed in this case library(proto) library(gsubfn) ## Wa ...

  9. idea中使用maven方式使用jetty+cmd中使用Jetty运行(maven)Web项目

    进度条件:必须是web项目 一.使用idea 导入项目或者打开(如果有可以忽略) 导入项目 . 全部next 导入成功,进行打开pom文件加入插件 <plugins> <!-- je ...

  10. 第29章 电容触摸屏—触摸画板—零死角玩转STM32-F429系列

    第29章     电容触摸屏—触摸画板 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/fir ...