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 = 2 });
                //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 = 2 });
                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 = 2 });
            }
        }

 

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 = 2 }).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 = 2 }, //參數
                     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 = 1;
                student_1.tel = "13323456765";
                Student student_2 = new Student();
                student_2.name = "名字哦1";
                student_2.sex = 1;
                student_2.tel = "13323456765";
                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) > 0)//多條插入,不使用事務的話,執行錯誤會導致臟數據
                    {
                        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", 20);
                para.Add("@res", 0, DbType.Int32, ParameterDirection.ReturnValue);//定義返回值
                var res1 = conn.Query("storedProcedure", para, null, true, null, CommandType.StoredProcedure).FirstOrDefault(); //只要using Dapper就可以直接用conn.Query()的形式
                para.Get<int>("@res");//獲取返回值
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM