可以使用擴展方法執(zhí)行查詢并使用動態(tài)類型映射結(jié)果。
匿名類型結(jié)果可以從以下擴展方法映射:
這些擴展方法可以從IDbConnection類型的任意對象中調(diào)用。
Query方法可以執(zhí)行查詢并將結(jié)果映射到動態(tài)類型列表。
string sql = "SELECT * FROM Invoice;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoices = connection.Query(sql).ToList();
}
QueryFirst方法可以執(zhí)行查詢并將第一個結(jié)果映射到動態(tài)類型列表。
string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QueryFirst(sql, new {InvoiceID = 1});
}
QueryFirstOrDefault方法可以執(zhí)行查詢并將第一個結(jié)果映射到動態(tài)類型列表,如果序列不包含任何元素則為默認值。
string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QueryFirstOrDefault(sql, new {InvoiceID = 1});
}
QuerySingle方法可以執(zhí)行查詢并將第一個結(jié)果映射到動態(tài)類型列表,如果序列中沒有元素則會引發(fā)異常。
string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QuerySingle(sql, new {InvoiceID = 1});
}
QuerySingleOrDefault方法可以執(zhí)行查詢并將第一個結(jié)果映射到動態(tài)類型列表,如果序列為空則為默認值;如果序列中有多個元素,則此方法將引發(fā)異常。
string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoice = connection.QuerySingleOrDefault(sql, new {InvoiceID = 1});
}
更多建議: