Dapper還使用了Async(異步)方法擴(kuò)展了IDbConnection接口:
我們只在本教程中添加了非異步版本,以便于閱讀。
var sql = "Invoice_Insert";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var affectedRows = connection.ExecuteAsync(sql,
new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
commandType: CommandType.StoredProcedure)
.Result;
}
var sql = "Invoice_Insert";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoices = connection.QueryAsync<Invoice>(sql).Result.ToList();
}
var sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QueryFirstAsync<Invoice>(sql, new {InvoiceID = 1}).Result;
}
var sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QueryFirstOrDefaultAsync<Invoice>(sql, new {InvoiceID = 1}).Result;
}
var sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QuerySingleAsync<Invoice>(sql, new {InvoiceID = 1}).Result;
}
var sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QuerySingleOrDefaultAsync<Invoice>(sql, new {InvoiceID = 1}).Result;
}
var sql = "SELECT * FROM Invoice; SELECT * FROM InvoiceItem;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
using (var multi = connection.QueryMultipleAsync(sql, new { InvoiceID = 1 }).Result)
{
var invoice = multi.Read<Invoice>().First();
var invoiceItems = multi.Read<InvoiceItem>().ToList();
}
}
更多建議: