C#中Dapper的使用教程
一、什麼是Dapper
Dapper是一款輕量級ORM工具(Github)。如果你在小的項目中,使用Entity Framework、NHibernate 來處理大數據訪問及關系映射,未免有點殺雞用牛刀。你又覺得ORM省時省力,這時Dapper 將是你不二的選擇。
二、Dapper的優點
- 輕量。隻有一個文件SqlMapper.cs,編譯後就40K的一個很小的Dll.
- 速度快。Dapper的速度接近與IDataReader,取列表的數據超過瞭DataTable。
- 支持多種數據庫。Dapper可以在所有Ado.net Providers下工作,包括sqlite, sqlce, firebird, oracle, MySQL, PostgreSQL and SQL Server
- 可以映射一對一,一對多,多對多等多種關系。
- 性能高。通過Emit反射IDataReader的序列隊列,來快速的得到和產生對象,性能不錯。
- 支持FrameWork2.0,3.0,3.5,4.0,4.5
- Dapper語法十分簡單。並且無須遷就數據庫的設計。
三、使用方法
1、添加NuGet程序包Dapper
2、配置文件添加連接數據庫的字符串
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/> </startup> <connectionStrings> <add name="MyStrConn" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DHR_DB;Integrated Security=True" /> </connectionStrings> </configuration>
3、添加DapperTools.cs(添加、批量添加、刪除、批量刪除、修改、批量修改、查詢、查詢in的操作、多語句操作)
// <copyright file="DapperTools.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace CSharpStudy { using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; internal class DapperTools { public static string ConnectionString = ConfigurationManager.ConnectionStrings["MyStrConn"].ConnectionString; /// <summary> /// 添加. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入實體類型.</param> /// <returns>int.</returns> public static int Add<T>(string sql, T t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Execute(sql, t); } } /// <summary> /// 批量添加. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入泛型類.</param> /// <returns>int.</returns> public static int Add<T>(string sql, List<T> t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Execute(sql, t); } } /// <summary> /// 刪除. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入實體類型.</param> /// <returns>int.</returns> public static int Delete<T>(string sql, T t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Execute(sql, t); } } /// <summary> /// 批量刪除. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入泛型類.</param> /// <returns>int.</returns> public static int Delete<T>(string sql, List<T> t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Execute(sql, t); } } /// <summary> /// 修改. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入實體類型.</param> /// <returns>int.</returns> public static int Update<T>(string sql, T t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Execute(sql, t); } } /// <summary> /// 批量修改. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入泛型類.</param> /// <returns>int.</returns> public static int Update<T>(string sql, List<T> t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Execute(sql, t); } } /// <summary> /// 查詢. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <returns>泛型類.</returns> public static List<T> Query<T>(string sql) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Query<T>(sql).ToList(); } } /// <summary> /// 查詢指定數據. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <param name="t">傳入泛型類.</param> /// <returns>類.</returns> public static T Query<T>(string sql, T t) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Query<T>(sql, t).SingleOrDefault(); } } /// <summary> /// 查詢的in操作. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> /// <returns>泛型類.</returns> public static List<T> Query<T>(string sql, int[] ids) where T : class { using (IDbConnection connection = new SqlConnection(ConnectionString)) { return connection.Query<T>(sql, new { ids }).ToList(); } } /// <summary> /// 多語句操作. /// </summary> /// <typeparam name="T">實體類型.</typeparam> /// <param name="sql">傳入sql執行語句.</param> public static void QueryMultiple(string sql) { using (IDbConnection connection = new SqlConnection(ConnectionString)) { var multiReader = connection.QueryMultiple(sql); var userInfo = multiReader.Read<UserInfo>(); var student = multiReader.Read<Student>(); multiReader.Dispose(); } } } }
4、添加測試類Student.cs、UserInfo。表數據自己添加
public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Memo { get; set; } public DateTime CreateTime { get; set; } public DateTime UpdateTime { get; set; } }
public class UserInfo { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Memo { get; set; } public DateTime CreateTime { get; set; } public DateTime UpdateTime { get; set; } }
5、調用方法
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> // <author>John Doe</author> //----------------------------------------------------------------------- namespace CSharpStudy { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; internal class Program { private static void Main(string[] args) { // --------------添加-------------- // UserInfo user = new UserInfo(); // user.Name = "九九"; // user.Age = 10; // user.Memo = "這是備註"; // user.CreateTime = DateTime.Now; // string sql = "Insert into UserInfo(Name,Age,Memo,CreateTime) values (@name, @Age, @Memo,@CreateTime)"; // int result = DapperTools.Add<UserInfo>(sql, user); // if (result > 0) // { // Console.WriteLine("添加成功"); // Console.ReadKey(); // } // --------------批量添加-------------- // UserInfo user = new UserInfo(); // user.Name = "李奎"; // user.Age = 50; // user.Memo = "這是備註"; // user.CreateTime = DateTime.Now; // UserInfo user2 = new UserInfo(); // user2.Name = "梁山伯"; // user2.Age = 54; // user2.Memo = "這是備註"; // user2.CreateTime = DateTime.Now; // List<UserInfo> list = new List<UserInfo>(); // list.Add(user); // list.Add(user2); // string sql = "Insert into UserInfo(Name,Age,Memo,CreateTime) values (@name, @Age, @Memo,@CreateTime)"; // int result = DapperTools.Add<UserInfo>(sql, list); // if (result > 0) // { // Console.WriteLine("添加成功"); // Console.ReadKey(); // } // --------------刪除-------------- // UserInfo user = new UserInfo(); // user.Id = 18; // string sql = "delete from UserInfo where Id=@Id"; // int result = DapperTools.Delete<UserInfo>(sql, user); // if (result > 0) // { // Console.WriteLine("刪除成功"); // Console.ReadKey(); // } // --------------批量刪除-------------- // UserInfo user = new UserInfo(); // user.Id = 15; // UserInfo user2 = new UserInfo(); // user2.Id = 16; // List<UserInfo> list = new List<UserInfo>(); // list.Add(user); // list.Add(user2); // string sql = "delete from UserInfo where Id=@Id"; // int result = DapperTools.Delete<UserInfo>(sql, list); // if (result > 0) // { // Console.WriteLine("添加成功"); // Console.ReadKey(); // } // --------------修改-------------- // UserInfo user = new UserInfo(); // user.Id = 14; // user.Name = "九九"; // string sql = "update UserInfo set Name=@Name,UpdateTime=GETDATE() where Id=@ID"; // int result = DapperTools.Update<UserInfo>(sql, user); // if (result > 0) // { // Console.WriteLine("修改成功"); // Console.ReadKey(); // } // --------------批量修改-------------- // UserInfo user = new UserInfo(); // user.Id = 13; // user.Name = "王文"; // UserInfo user2 = new UserInfo(); // user2.Id = 14; // user2.Name = "冰冰"; // List<UserInfo> list = new List<UserInfo>(); // list.Add(user); // list.Add(user2); // string sql = "update UserInfo set Name=@Name,UpdateTime=GETDATE() where Id=@ID"; // int result = DapperTools.Update<UserInfo>(sql, list); // if (result > 0) // { // Console.WriteLine("修改成功"); // Console.ReadKey(); // } // --------------查詢-------------- // string sql = "select * from UserInfo"; // List<UserInfo> list = DapperTools.Query<UserInfo>(sql); // foreach (var item in list) // { // Console.WriteLine(item.Id + "-" + item.Name + "-" + item.Age + "-" + item.Memo); // } // Console.ReadKey(); // --------------查詢指定數據-------------- // UserInfo user = new UserInfo(); // user.Id = 14; // string sql = "select * from UserInfo where Id=@Id"; // UserInfo userInfo = DapperTools.Query<UserInfo>(sql, user); // Console.WriteLine(userInfo.Id + "-" + userInfo.Name + "-" + userInfo.Age + "-" + userInfo.Memo); // Console.ReadKey(); // --------------查詢的in操作-------------- // string sql = "select * from UserInfo where Id in @ids"; // int[] ids = { 1, 2 }; // List<UserInfo> list = DapperTools.Query<UserInfo>(sql, ids); // foreach (var item in list) // { // Console.WriteLine(item.Id + "-" + item.Name + "-" + item.Age + "-" + item.Memo); // } // --------------多語句操作-------------- // string sql = "select * from userinfo;select * from student"; // DapperTools.QueryMultiple(sql); } } }
源代碼:
鏈接: https://pan.baidu.com/s/1IM3diCqJCoSpvr11H6zddQ
提取碼: 6ag9
後續會陸續更新其他資料,喜歡請關註哦!
我的博客:https://www.cnblogs.com/duhaoran
到此這篇關於C# Dapper的使用的文章就介紹到這瞭,更多相關C#使用Dapper內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 輕量級ORM框架Dapper應用之實現In操作
- 輕量級ORM框架Dapper應用支持操作函數和事物
- C# 中對象序列化XML的方法
- c# 使用Json.NET實現json序列化
- 詳解C#對Dictionary內容的通用操作