Dapper 是一个轻量级的 ORM(对象关系映射)工具,在 ASP.NET 中使用 Dapper 可以高效地进行数据库操作。下面为你介绍一些 Dapper 的高级用法。
1. 多映射(Multi-Mapping)
多映射允许你将查询结果映射到多个对象。例如,一个查询可能返回多个表的数据,你可以将其映射到不同的对象。
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Dapper;
// 定义实体类
public class Order
{
public int OrderId { get; set; }
public string OrderNumber { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main()
{
string connectionString = "YourConnectionString";
using (var connection = new SqlConnection(connectionString))
{
string sql = "SELECT o.OrderId, o.OrderNumber, c.CustomerId, c.Name " +
"FROM Orders o " +
"JOIN Customers c ON o.CustomerId = c.CustomerId";
var orders = connection.Query<Order, Customer, Order>(
sql,
(order, customer) =>
{
order.Customer = customer;
return order;
},
splitOn: "CustomerId");
foreach (var order in orders)
{
Console.WriteLine($"Order Number: {order.OrderNumber}, Customer Name: {order.Customer.Name}");
}
}
}
}
在上述代码里,Query
方法的泛型参数指定了查询结果要映射的对象类型。splitOn
参数指明了在哪个列进行分割,从而把结果映射到不同的对象。
2. 批量插入(Bulk Insert)
Dapper 支持批量插入数据,这样能提升插入大量数据时的性能。
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Dapper;
// 定义实体类
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
class Program
{
static void Main()
{
string connectionString = "YourConnectionString";
using (var connection = new SqlConnection(connectionString))
{
var products = new List<Product>
{
new Product { Name = "Product 1", Price = 10.0m },
new Product { Name = "Product 2", Price = 20.0m },
new Product { Name = "Product 3", Price = 30.0m }
};
string sql = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";
connection.Execute(sql, products);
}
}
}
此代码中,Execute
方法接收一个 SQL 语句和一个对象列表,Dapper 会自动将列表中的对象属性映射到 SQL 语句的参数上,进而实现批量插入。
3. 存储过程调用(Stored Procedure Call)
Dapper 可以方便地调用存储过程。
using System;
using System.Data.SqlClient;
using Dapper;
// 定义实体类
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main()
{
string connectionString = "YourConnectionString";
using (var connection = new SqlConnection(connectionString))
{
var parameters = new { DepartmentId = 1 };
var employees = connection.Query<Employee>("GetEmployeesByDepartment", parameters, commandType: System.Data.CommandType.StoredProcedure);
foreach (var employee in employees)
{
Console.WriteLine($"Employee Name: {employee.Name}");
}
}
}
}
在这段代码中,Query
方法的 commandType
参数设置为 StoredProcedure
,表明要执行的是一个存储过程。同时,使用匿名对象传递存储过程的参数。
4. 动态查询(Dynamic Query)
Dapper 支持动态构建查询,这在需要根据不同条件构建查询语句时很有用。
using System;
using System.Data.SqlClient;
using Dapper;
using System.Dynamic;
class Program
{
static void Main()
{
string connectionString = "YourConnectionString";
using (var connection = new SqlConnection(connectionString))
{
var parameters = new ExpandoObject();
string sql = "SELECT * FROM Customers";
bool filterByCountry = true;
if (filterByCountry)
{
sql += " WHERE Country = @Country";
((IDictionary<string, object>)parameters).Add("Country", "USA");
}
var customers = connection.Query(sql, parameters);
foreach (var customer in customers)
{
Console.WriteLine($"Customer Name: {customer.Name}");
}
}
}
}
在上述代码中,使用 ExpandoObject
动态构建查询参数。依据不同条件,动态地修改 SQL 语句并添加参数。
5. 事务处理(Transaction Handling)
Dapper 可以与 ADO.NET 的事务处理结合使用,保证数据操作的原子性。
using System;
using System.Data.SqlClient;
using Dapper;
class Program
{
static void Main()
{
string connectionString = "YourConnectionString";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
string sql1 = "INSERT INTO Table1 (Column1) VALUES (@Value)";
connection.Execute(sql1, new { Value = "Data1" }, transaction: transaction);
string sql2 = "INSERT INTO Table2 (Column1) VALUES (@Value)";
connection.Execute(sql2, new { Value = "Data2" }, transaction: transaction);
transaction.Commit();
Console.WriteLine("Transaction committed successfully.");
}
catch (Exception ex)
{
transaction.Rollback();
Console.WriteLine($"Transaction rolled back due to error: {ex.Message}");
}
}
}
}
}
在这个代码示例中,使用 BeginTransaction
方法开启一个事务,在事务中执行多个数据操作。若操作成功,调用 Commit
方法提交事务;若出现异常,则调用 Rollback
方法回滚事务。