參考資料:Cooper Liu 毒逆天
一、Dapper安裝
添加引用-->NuGet管理-->搜索Dapper-->安裝
二、新建表

--創建一個員工表 create table Employee ( Em_Id int identity(1,1) primary key, Em_Name varchar(50) not null, Em_Age int default(18) not null ) --部門表 Create Table Department ( Depart_Id int identity(1,1) primary key, Depart_Name varchar(20) not null, ) --員工所屬部門關系表 Create table EmployeePartment ( EP_Id int identity(1,1) primary key, Em_Id int not null, Depart_Id int not null )
三、新建實體類
實體類屬性要與數據庫中的字段名稱對應

/// <summary> /// 生成Employee實體,注意類屬性與表字段要一一對應 /// </summary> public class Employee { public int Em_Id { get; set; } public string Em_Name { get; set; } public int Em_Age { get; set; } } /// <summary> /// 生成部門Department實體 /// </summary> public class Department { public int Depart_Id { get; set; } public string Depart_Name { get; set; } } /// <summary> /// 生成部門員工所屬部門對應關系 /// </summary> public class EmployeePartment { public int EP_Id { get; set; } public int Em_Id { get; set; } public int Depart_Id { get; set; } }
四、插入操作
Dapper支持單個插入,也支持批量插入(Bulk),支持存儲過程進行插入操作。

/// <summary> /// 聲明object類型可用單個對象時插入單對象,也可批量BulkInsert插入(只要實現IEnumable接口) /// </summary> /// <param name="obj"></param> private static void InsertEmployee(Object obj) { using (var conn = GetConnection()) { string sql = "insert into employee values (@Em_Name,@Em_Age)"; int result = conn.Execute(sql, obj); } } /// <summary> /// 插入部門操作 /// </summary> /// <param name="depart"></param> private static void InsertDepartment(object depart) { CommandDefinition command = new CommandDefinition("insert into department values (@Depart_Name)", depart); using (var conn=GetConnection()) { conn.Execute(command); } } /// <summary> /// 生成sqlConnection對象。返回IDbConnection. /// </summary> /// <returns></returns> private static IDbConnection GetConnection() { var conn = new SqlConnection(connstr); return conn; }
示例中使用了conn.Execute()方法,該方法兩個種形式的重載。
1、public static int Execute(this IDbConnection cnn, CommandDefinition command);
2、public static int Execute(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);
雖說是兩種形式,其實質是CommandDefinition對重載的第二個方法條件進行了封閉。由CommandDefinition構造函數定義可以看到對應關系。
public CommandDefinition(string commandText, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null, CommandFlags flags = CommandFlags.Buffered);
Execute是IDbConnection的擴展方法,所以conn可以直接調用。
五、刪除操作
Dapper支持sql語句刪除操作,也支持存儲過程刪除操作

//此處為方法調用 //Ado.net方法刪除 DeleteEmployeeById(1); UseCommandDeleteEmployeeUseById(2); //存儲過程刪除 ProcDeleteEmployeeById(3); //此處為方法實現 /// <summary> /// 根據ID刪除對應Employee /// </summary> /// <param name="id">待刪除的EmployeeId</param> private static void DeleteEmployeeById(int id) { using (var conn=GetConnection()) { int result= conn.Execute("delete from Employee where EM_Id=@id", new { @id = id }); } } /// <summary> /// 使用Command形式刪除操作 /// </summary> /// <param name="id">待刪除的Employee的ID</param> private static void UseCommandDeleteEmployeeUseById(int id) { var command = new CommandDefinition("delete from Employee where Em_Id=@Eid", new { @Eid = id }, null, null, CommandType.Text,CommandFlags.None); using (var conn=GetConnection()) { int result = conn.Execute(command); } } /// <summary> /// 使用存儲過程形式刪除Employee /// </summary> /// <param name="id">待刪除的Employee</param> private static void ProcDeleteEmployeeById(int id) { using (var conn = GetConnection()) { int result= conn.Execute("pr_delete_employee", new { @id = id },null,null,CommandType.StoredProcedure); } }
刪除示例中也是使用conn.Execute()方法進行操作。
六、更新操作
操作同新增、刪除同樣使用conn.Execute()方法進行。

//方法調用 UpdateEmployeeName(4, "新名稱"); UseCommandUpdateEmployee(4, 18); ProcUpdateEmployeeName(5, "舊名稱"); //方法實現 /// <summary> /// 更新指定ID名稱為新值 /// </summary> /// <param name="eid">Employee的Id</param> /// <param name="name">新的employee名稱</param> private static void UpdateEmployeeName(int eid, string name) { using (var conn=GetConnection()) { int result= conn.Execute("update Employee set Em_Name=@name where Em_Id=@id", new { @name = name, @id = eid }); } } /// <summary> /// 使用Command形式更新Employee信息 /// </summary> /// <param name="eid">待更新的EmployeeId</param> /// <param name="Age">Age新值</param> private static void UseCommandUpdateEmployee(int eid, int Age) { var command=new CommandDefinition("update Employee set Em_Age=@age where em_Id=@eid",new{@age=Age,@eid=eid},null,null,CommandType.Text,CommandFlags.None); using (var conn=GetConnection()) { int result = conn.Execute(command); } } /// <summary> /// 更新指定ID名稱為新值 /// </summary> /// <param name="eid">Employee的Id</param> /// <param name="name">新的employee名稱</param> private static void ProcUpdateEmployeeName(int eid, string name) { using (var conn = GetConnection()) { var p = new DynamicParameters(); p.Add("@id", eid); p.Add("@name", name); int result = conn.Execute("pr_update_employee", new { id = eid,name = name },null,null,CommandType.StoredProcedure)); } }
七、查找操作

//簡單查詢 Employee employee = GetEmployeeById(5); if (employee != null) { Console.WriteLine("ID為5的員工已找到名稱:" + employee.Em_Name); } //子查詢 List<Employee> list_employees = GetEmployeesByPartId(1); Console.WriteLine("共找到{0}記錄:", list_employees.Count); for (int i = 0; i < list_employees.Count; i++) { Console.Write(list_employees[i].Em_Name + ","); } //多返回值 GetMutile(); /// <summary> /// 根據ID查找EmpolyeeID 支持ADO語句和存儲過程 /// </summary> /// <param name="id"></param> /// <returns></returns> private static Employee GetEmployeeById(int id) { Employee employee = new Employee(); using (var conn = GetConnection()) { employee = conn.Query<Employee>("select * from employee where Em_Id=@id", new { id = id }).FirstOrDefault(); } //CommandDefinition command = new CommandDefinition("select * from employee wehre em_id=@id"); //using (var conn = GetConnection()) //{ // employee = conn.Query<Employee>(command).FirstOrDefault(); //} return employee; } /// <summary> /// 子查詢 /// </summary> /// <param name="partid"></param> /// <returns></returns> private static List<Employee> GetEmployeesByPartId(int partid) { List<Employee> employees = new List<Employee>(); CommandDefinition command = new CommandDefinition("select * from employee where em_id in (select em_id from EmployeePARTMENT where Depart_Id=@id) ", new { id = partid }); using (var conn = GetConnection()) { employees = conn.Query<Employee>(command).ToList(); } return employees; } /// <summary> /// 多返回值查詢 /// </summary> private static void GetMutile() { string sql = @"select * from [Employee]; select * from [Department]"; CommandDefinition command = new CommandDefinition(sql); using (var conn = GetConnection()) { var muitle = conn.QueryMultiple(sql); //var muitle=conn.QueryMultiple(command); if (!muitle.IsConsumed) { //強類型讀取 //var employees = muitle.Read<Employee>(); //var deparements = muitle.Read<Department>(); //動態類型讀取 var employees = muitle.Read(); var deparements = muitle.Read(); foreach (var item in employees) { Console.WriteLine(item.Em_Name + ":" + item.Em_Age.ToString()); } Console.WriteLine(); foreach (var item in deparements) { Console.WriteLine(item.Depart_Name + ":" + item.Depart_Id); } } } }
八、總結
使用Dapper進行增刪改查、存儲過程調用、多表值返回操作。