可以使用擴(kuò)展方法執(zhí)行查詢并使用動(dòng)態(tài)類型映射結(jié)果。
強(qiáng)類型結(jié)果可以從以下擴(kuò)展方法映射:
這些擴(kuò)展方法可以從IDbConnection類型的任意對(duì)象中調(diào)用。
Query方法可以執(zhí)行查詢并將結(jié)果映射到強(qiáng)類型列表。
string sql = "SELECT TOP 10 * FROM OrderDetails";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDetails = connection.Query<OrderDetail>(sql).ToList();
Console.WriteLine(orderDetails.Count);
FiddleHelper.WriteTable(orderDetails);
}
QueryFirst方法可以執(zhí)行查詢并將第一個(gè)結(jié)果映射到強(qiáng)類型列表。
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDetail = connection.QueryFirst<OrderDetail>(sql, new {OrderDetailID = 1});
FiddleHelper.WriteTable( new List<OrderDetail>() { orderDetail });
}
QueryFirstOrDefault方法可以執(zhí)行查詢并將第一個(gè)結(jié)果映射到強(qiáng)類型列表,如果序列不包含任何元素則為默認(rèn)值。
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDetail = connection.QueryFirstOrDefault<OrderDetail>(sql, new {OrderDetailID = 1});
FiddleHelper.WriteTable(new List<OrderDetail>() { orderDetail });
}
QuerySingle方法可以執(zhí)行查詢并將第一個(gè)結(jié)果映射到強(qiáng)類型列表,如果序列中沒有元素則會(huì)引發(fā)異常。
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDetail = connection.QuerySingle<OrderDetail>(sql, new {OrderDetailID = 1});
FiddleHelper.WriteTable(new List<OrderDetail>() { orderDetail });
}
QuerySingleOrDefault方法可以執(zhí)行查詢并將第一個(gè)結(jié)果映射到強(qiáng)類型列表,如果序列為空則為默認(rèn)值;如果序列中有多個(gè)元素,則此方法將引發(fā)異常。
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDetail = connection.QuerySingleOrDefault<OrderDetail>(sql, new {OrderDetailID = 1});
FiddleHelper.WriteTable(new List<OrderDetail>() { orderDetail });
}
更多建議: