Dapper是一個輕量級的ORM(對象關系映射)庫,用于.NET應用程序與數據庫之間的數據訪問。它允許你使用SQL查詢來執行數據庫操作,而不需要復雜的映射配置。在這篇文章中,我將為您提供Dapper的高級應用功能示例,每個示例都有源代碼和注釋。這些示例將涵蓋Dapper的一些高級功能,以幫助你更好地理解如何在實際應用中使用它。
Dapper允許你輕松執行多表關聯查詢。在這個示例中,我們將查詢兩個表,一個是Customers表,另一個是Orders表,并將它們關聯起來。
using Dapper;using System;using System.Data;using System.Data.SqlClient;using System.Linq;public class Customer{ public int CustomerId { get; set; } public string CustomerName { get; set; }}public class Order{ public int OrderId { get; set; } public int CustomerId { get; set; } public decimal TotalAmount { get; set; }}class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); string query = "SELECT c.CustomerId, c.CustomerName, o.OrderId, o.TotalAmount " + "FROM Customers c " + "JOIN Orders o ON c.CustomerId = o.CustomerId"; var result = dbConnection.Query<Customer, Order, Customer>( query, (customer, order) => { customer.Orders = order; return customer; }, splitOn: "OrderId" ); foreach (var customer in result) { Console.WriteLine($"Customer ID: {customer.CustomerId}, Name: {customer.CustomerName}"); Console.WriteLine($"Order ID: {customer.Orders.OrderId}, Total Amount: {customer.Orders.TotalAmount}"); Console.WriteLine(); } }}
Dapper允許你使用事務來確保一組操作要么全部成功,要么全部失敗。在這個示例中,我們將演示如何在Dapper中使用事務。
using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); dbConnection.Open(); using var transaction = dbConnection.BeginTransaction(); try { string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)"; string updateQuery = "UPDATE Customers SET CustomerName = @CustomerName WHERE CustomerId = @CustomerId"; var product = new { Name = "ProductX", Price = 19.99 }; var customer = new { CustomerName = "NewName", CustomerId = 1 }; dbConnection.Execute(insertQuery, product, transaction: transaction); dbConnection.Execute(updateQuery, customer, transaction: transaction); // Commit the transaction if all operations are successful transaction.Commit(); Console.WriteLine("Transaction committed."); } catch (Exception ex) { // Rollback the transaction if any operation fails transaction.Rollback(); Console.WriteLine("Transaction rolled back. Error: " + ex.Message); } }}
Dapper允許你自定義數據類型到.NET類型的映射。在這個示例中,我們將使用TypeHandler來自定義Point類型的映射。
using Dapper;using System;using System.Data;using System.Data.SqlClient;using Npgsql;using NpgsqlTypes;public class Point{ public double X { get; set; } public double Y { get; set; }}public class PointTypeHandler : SqlMapper.TypeHandler<Point>{ public override void SetValue(IDbDataParameter parameter, Point value) { parameter.Value = $"({value.X},{value.Y})"; parameter.DbType = DbType.String; } public override Point Parse(object value) { if (value is string strValue) { var parts = strValue.Trim('(', ')').Split(','); if (parts.Length == 2 && double.TryParse(parts[0], out double x) && double.TryParse(parts[1], out double y)) { return new Point { X = x, Y = y }; } } return null; }}class Program{ static void Main() { SqlMapper.AddTypeHandler(new PointTypeHandler()); string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new NpgsqlConnection(connectionString); string query = "SELECT PointColumn FROM MyTable WHERE Id = @Id"; var result = dbConnection.Query<Point>(query, new { Id = 1 }).FirstOrDefault(); if (result != null) { Console.WriteLine($"X: {result.X}, Y: {result.Y}"); } else { Console.WriteLine("Point not found."); } }}
Dapper支持批量插入數據,這對于大規模數據操作非常有用。在這個示例中,我們將演示如何批量插入多個產品記錄。
using Dapper;using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;public class Product{ public string Name { get; set; } public decimal Price { get; set; }}class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); dbConnection.Open(); var products = new List<Product> { new Product { Name = "ProductA", Price = 10.99m }, new Product { Name = "ProductB", Price = 15.99m }, new Product { Name = "ProductC", Price = 20.99m } }; string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)"; int rowsAffected = dbConnection.Execute(insertQuery, products); Console.WriteLine($"{rowsAffected} rows inserted."); }}
雖然Dapper通常用于執行SQL查詢,但你也可以執行自定義的SQL語句,例如存儲過程或函數調用。在這個示例中,我們將演示如何執行一個存儲過程。
using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); string storedProcedure = "MyStoredProcedure"; var parameters = new DynamicParameters(); parameters.Add("Param1", 123); parameters.Add("Param2", "TestValue", DbType.String, ParameterDirection.Input, 50); var result = dbConnection.Query<int>(storedProcedure, parameters, commandType: CommandType.StoredProcedure).FirstOrDefault(); Console.WriteLine($"Stored procedure result: {result}"); }}
你可以使用Dapper的Execute方法來執行自定義的SQL語句,而不僅僅是查詢。在這個示例中,我們將演示如何執行一個自定義的更新語句。
using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); string updateStatement = "UPDATE Customers SET CustomerName = @NewName WHERE CustomerId = @CustomerId"; var parameters = new { NewName = "NewName", CustomerId = 1 }; int rowsAffected = dbConnection.Execute(updateStatement, parameters); Console.WriteLine($"{rowsAffected} rows updated."); }}
Dapper支持異步查詢,這對于高并發應用程序非常有用。在這個示例中,我們將演示如何使用異步方法執行查詢。
using Dapper;using System;using System.Data;using System.Data.SqlClient;using System.Threading.Tasks;class Program{ static async Task Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); string query = "SELECT * FROM Products"; var products = await dbConnection.QueryAsync<Product>(query); foreach (var product in products) { Console.WriteLine($"Name: {product.Name}, Price: {product.Price}"); } }}
你可以使用Dapper的Table特性來指定實體類與數據庫中不同表之間的映射關系。在這個示例中,我們將演示如何自定義表名。
using Dapper;using System;using System.Data;using System.Data.SqlClient;[Table("MyCustomTableName")]public class CustomTable{ public int Id { get; set; } public string Name { get; set; }}class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); string query = "SELECT * FROM MyCustomTableName"; var result = dbConnection.Query<CustomTable>(query); foreach (var item in result) { Console.WriteLine($"Id: {item.Id}, Name: {item.Name}"); } }}
Dapper默認使用@作為參數前綴,但你可以自定義參數前綴。在這個示例中,我們將演示如何自定義參數前綴為$。
using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{ static void Main() { SqlMapperExtensions.Configure("$$$"); // 設置參數前綴為 $$$ string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); string query = "SELECT * FROM Products WHERE Name = $$$productName"; var result = dbConnection.Query<Product>(query, new { productName = "ProductA" }); foreach (var product in result) { Console.WriteLine($"Name: {product.Name}, Price: {product.Price}"); } }}
Dapper使分頁查詢變得容易,你可以使用LIMIT和OFFSET來執行分頁查詢。在這個示例中,我們將演示如何執行分頁查詢。
using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{ static void Main() { string connectionString = "YourConnectionStringHere"; using IDbConnection dbConnection = new SqlConnection(connectionString); int pageSize = 10; int pageNumber = 2; string query = "SELECT * FROM Products ORDER BY ProductId OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY"; var result = dbConnection.Query<Product>(query, new { Offset = (pageNumber - 1) * pageSize, PageSize = pageSize }); foreach (var product in result) { Console.WriteLine($"Name: {product.Name}, Price: {product.Price}"); } }}
這些示例演示了Dapper的一些高級功能,包括多表關聯查詢、事務處理、自定義類型映射、批量插入、自定義SQL語句、異步查詢、自定義表名、自定義參數前綴和查詢分頁。通過這些示例,你可以更好地了解如何在實際應用中充分利用Dapper來簡化數據訪問任務。
本文鏈接:http://www.www897cc.com/showinfo-26-74665-0.html.NET輕量級ORM框架Dapper.NET的高級應用實例詳解
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 學到了!Figma 原來是這樣表示矩形的
下一篇: 文件系統那些事兒,你學會了嗎?