Dapper学习笔记

资料

  • DLL链接:https://pan.baidu.com/s/1JEvBu1kCqVc1vN49uuYEAw 提取码:frv5

MySQLHelper

  • 一定要提前设置一下数据库类型(SetDBType()),否则某些dapper的扩展方法或sql语句会报语法错误
  • dapper默认是sqlserver
  • SetDBType()只需在所有数据库操作之前执行一次即可
using System;
using System.Data;
using Dapper;
using MySql.Data.MySqlClient;

using MS.Base;

namespace MS.DBUtil
{
    public class MySQLHelper
    {
        private static readonly string connString = System.Configuration.ConfigurationManager.ConnectionStrings["connString"].ToString();

        private static void SetDBType()
        {
            Dapper.SimpleCRUD.SetDialect(Dapper.SimpleCRUD.Dialect.MySQL);
        }

        static MySQLHelper()
        {
            SetDBType();
        }

        public static IDbConnection Conn
        {
            get 
            {
                return new MySqlConnection(connString); 
            }
        }
    }
}

实体类

  • Key、Column等特性需要添加Dapper.SimpleCRUD的静态引用
  • 通过Table、Column来将实体类与数据库不对应的字段对应起来,Key标识主键
  • 扩展属性通过NotMapped, IgnoreInsert, IgnoreSelect, IgnoreUpdate来标识忽略,const字段自动忽略
using Dapper;

namespace MS.Models
{
    [Serializable]
    [Table("ms_employee")]
    public class EmployeeModel
    {
        [Key]
        [Column("Id")]
        public string Id { get; set; }
        [Column("DepartmentId")]
        public string DepartmentId { get; set; }
        [IgnoreInsert,IgnoreSelect,IgnoreUpdate]
        public string DepartmentName { get; set; }
        [Column("EmployeeNo")]
        public string EmployeeNo { get; set; }
        [Column("EmployeeName")]
        public string EmployeeName { get; set; }
        [Column("EmployeeSex")]
        public string EmployeeSex { get; set; }

        private string _employeeBirth = string.Empty;
        [Column("EmployeeBirth")]
        public string EmployeeBirth
        {
            get
            {
                return this._employeeBirth;
            }
            set
            {
                this._employeeBirth = Convert.ToDateTime(value).ToString("yyyy-MM-dd");
            }
        }
        [Column("IsJob")]
        public bool IsJob { get; set; }
        [Column("Remarks")]
        public string Remarks { get; set; }
        [NotMapped, IgnoreInsert, IgnoreSelect, IgnoreUpdate]
        public DepartmentModel CorrespondingDepartment { get; set; }
    }
}
using Dapper;

namespace MS.Models
{
    [Serializable]
    [Table("ms_department")]
    public class DepartmentModel
    {
        [Key]
        [Column("Id")]
        public string Id { get; set; }
        [Column("DepartmentNo")]
        public string DepartmentNo { get; set; }
        [Column("DepartmentName")]
        public string DepartmentName { get; set; }
        [Column("Remarks")]
        public string Remarks { get; set; }
    }
}

DAL

  • 使用Get、GetList、Update等方法前,一定要正确设置数据库类型

public int AddEmployee(EmployeeModel employee)
{
    StringBuilder sql = new StringBuilder("INSERT INTO ms_employee(Id,DepartmentId,EmployeeNo,EmployeeName,EmployeeSex,EmployeeBirth,IsJob,Remarks)");
    sql.Append(" VALUES(@Id,@DepartmentId,@EmployeeNo,@EmployeeName,@EmployeeSex,@EmployeeBirth,@IsJob,@Remarks);");
    int add_Result = 0;
    try
    {
        using (this.Conn)
        {
            add_Result = this.Conn.Execute(sql.ToString(), employee);
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }

    return add_Result;
}

/// 
/// 根据Id(主键),删除员工
/// 
/// 
/// 
public int DeleteEmployeeById(string id)
{
    int delete_Result = 0;
    EmployeeModel model = new EmployeeModel();
    model.Id = id;
    try
    {
        using (this.Conn)
        {
            delete_Result = this.Conn.Delete(model);
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return delete_Result;
}
        
public int DeleteEmployeeByNo(string employeeNo)
{
    int delete_Result = 0;
    string sql = "DELETE FROM ms_employee WHERE EmployeeNo=@EmployeeNo;";
    try
    {
        using (this.Conn)
        {
            delete_Result = this.Conn.Execute(sql, new { EmployeeNo = employeeNo });
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return delete_Result;
}

public int ModfiyEmployeeInfo(EmployeeModel employee)
{
    int modify_Result = 0;
    try
    {
        using (this.Conn)
        {
            modify_Result = this.Conn.Update(employee);
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return modify_Result;
}

单表查询

/// 
/// 根据主键Id获取指定部门
/// 
/// 
/// 
public DepartmentModel GetSpecifyDepartmentById(string id)
{
    DepartmentModel model = null;
    try
    {
        using (this.Conn)
       {
            model = this.Conn.Get(id);
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return model;
}

/// 
/// 根据部门编号(唯一键),获取部门
/// 
/// 
/// 
public DepartmentModel GetSpecifyDepartmentByDepartmentNo(string no)
{
    DepartmentModel model = null;
    string sql = "SELECT * FROM ms_department WHERE DepartmentNo = @DepartmentNo;";
    try
    {
        using (this.Conn)
        {
            model = this.Conn.Query(sql, new { DepartmentNo = no }).SingleOrDefault();
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return model;
}
        
/// 
/// 获取所有部门信息
/// 
/// 
public List GetDepartments()
{
    List departments = new List();
    try
    {
        using (this.Conn)
        {
            departments = this.Conn.GetList().ToList();
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return departments;
}
        
/// 
/// 查询给定的部门编号是否存在
/// 
/// 
/// true:已存在 false:未存在
public bool CheckDepartmentNoIsExist(string departmentNo)
{
    bool result = true;
    try
    {
        using (this.Conn)
        {
           string sql = "SELECT COUNT(*) FROM ms_department WHERE DepartmentNo = @DepartmentNo;";
            result = this.Conn.ExecuteScalar(sql, new { DepartmentNo = departmentNo }) > 0;
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
        throw ex;
    }
    return result;
}

多表联查

  • 注意SplitOn的使用规范
/// 
/// 获取全部员工
/// 
/// 
public List GetEmployees()
{
    StringBuilder sql = new StringBuilder("SELECT * FROM ms_employee e");
    sql.Append(" INNER JOIN ms_department d");
    sql.Append(" ON d.Id = e.DepartmentId;");

    List models = new List();
    try
    {
        using (this.Conn)
        {
            models = this.Conn.Query(sql.ToString(), (employee, dp) =>
                {
                    employee.DepartmentName = dp.DepartmentName;
                    employee.CorrespondingDepartment = dp;
                    return employee;
                }).ToList();
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return models;
}
        
/// 
/// 根据员工编号(唯一键),查询员工
/// 
/// 
/// 
public EmployeeModel GetSpecifyEmployeeByEmployeeNo(string employeeNo)
{
    StringBuilder sql = new StringBuilder("SELECT");
    sql.Append(" e.Id,e.DepartmentId,d.DepartmentName,e.EmployeeNo,e.EmployeeName,e.EmployeeSex,e.EmployeeBirth,e.IsJob,e.Remarks");
    sql.Append(" ,d.Id, d.DepartmentNo, d.DepartmentName, d.Remarks");
    sql.Append(" FROM ms_employee e");
    sql.Append(" INNER JOIN ms_department d ON d.Id = e.DepartmentId");
    sql.Append(" WHERE EmployeeNo = @EmployeeNo;");
    EmployeeModel model = null;
    try
    {
        using (this.Conn)
        {
            model = this.Conn.Query(sql.ToString(), (employee, dp) =>
            {
                employee.CorrespondingDepartment = dp;
                return employee;
            }, new { EmployeeNo = employeeNo }, splitOn: "Id").SingleOrDefault();
            /* splitOn:从查询的字段列表最后向前,到splitOn指定的第一个列名,映射到最后一张表
             * 接着到splitOn指定的第二个列名,映射到最后第二张表,以此类推
             * splitOn:"列名1,列名2,..."
             */
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
    return model;
}

你可能感兴趣的:(数据库,ORM)