结果强类型
描述
可以使用扩展方法执行查询并使用动态类型映射结果。
强类型结果可以从以下扩展方法映射:
- Query
- QueryFirst
- QueryFirstOrDefault
- QuerySingle
- QuerySingleOrDefault
这些扩展方法可以从IDbConnection类型的任意对象中调用。
案例 - Query
Query方法可以执行查询并将结果映射到强类型列表。
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
QueryFirst方法可以执行查询并将第一个结果映射到强类型列表。
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
QueryFirstOrDefault方法可以执行查询并将第一个结果映射到强类型列表,如果序列不包含任何元素则为默认值。
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
QuerySingle方法可以执行查询并将第一个结果映射到强类型列表,如果序列中没有元素则会引发异常。
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
QuerySingleOrDefault方法可以执行查询并将第一个结果映射到强类型列表,如果序列为空则为默认值;如果序列中有多个元素,则此方法将引发异常。
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 });
}