使用方法类似于同步方法。
dapper查询方法默认开启缓存,这样会加快第二次以后的查询速度,但是对于查询数据量比较巨大的结果,比如select * from xx
去掉缓存可以减轻内存的压力。
string sql = "SELECT * FROM OrderDetails;";
using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
var orderDetails = connection.Query<OrderDetail>(sql, buffered: false).ToList();
FiddleHelper.WriteTable(orderDetails.Take(10));
}
1.开启事务
string sql = "INSERT INTO Customers (CustomerName) Values (@CustomerName);";
using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var affectedRows = connection.Execute(sql, new {CustomerName = "Mark"}, transaction: transaction);
transaction.Commit();
Console.WriteLine(affectedRows);
}
}
2.开启事务范围
// using System.Transactions;
using (var transaction = new TransactionScope())
{
var sql = "Invoice_Insert";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var affectedRows = connection.Execute(sql,
new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
commandType: CommandType.StoredProcedure);
}
transaction.Complete();
}
一次执行:
var sql = "Invoice_Insert";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var affectedRows = connection.Execute(sql,
new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
commandType: CommandType.StoredProcedure);
My.Result.Show(affectedRows);
}
批量执行:
var sql = "Invoice_Insert";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var affectedRows = connection.Execute(sql,
new[]
{
new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_1"},
new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_2"},
new {Kind = InvoiceKind.StoreInvoice, Code = "Many_Insert_3"}
},
commandType: CommandType.StoredProcedure
);
My.Result.Show(affectedRows);
}