Query方法是一种扩展方法,可以从IDbConnection类型的任何对象中调用。它可以执行查询并映射结果。
结果可以映射到:
- 匿名类型
- 强类型
- 多映射(一对一)
- 多映射 (一对多)
- 多类型
参数
下表显示了Query方法的不同参数。
名称 | 描述 |
---|---|
SQL | 要执行的查询 |
PARAM | 查询参数(默认= null) |
Transaction | 要使用的事务(default = null)。 |
buffered | 是否缓存,默认为true |
CommandTimeout | 命令超时,默认为null |
commandType | 命令类型,是存储过程,还是SQL语句,默认为null |
示例:查询匿名
可以使用Query方法执行原始SQL查询,并将结果映射到动态列表。
string sql = "SELECT TOP 10 * FROM OrderDetails";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDetail = connection.Query(sql).FirstOrDefault();
FiddleHelper.WriteTable(orderDetail);
}
示例:强类型查询
可以使用Query方法执行原始SQL查询,并将结果映射到强类型列表。
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);
}
示例:查询多映射(一对一)
可以使用Query方法执行原始SQL查询,并将结果映射到具有一对一关系的强类型列表。
string sql = "SELECT * FROM Invoice AS A INNER JOIN InvoiceDetail AS B ON A.InvoiceID = B.InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoices = connection.Query<Invoice, InvoiceDetail, Invoice>(
sql,
(invoice, invoiceDetail) =>
{
invoice.InvoiceDetail = invoiceDetail;
return invoice;
},
splitOn: "InvoiceID")
.Distinct()
.ToList();
}
示例:查询多映射(一对多)
string sql = "SELECT TOP 10 * FROM Orders AS A INNER JOIN OrderDetails AS B ON A.OrderID = B.OrderID;";
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var orderDictionary = new Dictionary<int, Order>();
var list = connection.Query<Order, OrderDetail, Order>(
sql,
(order, orderDetail) =>
{
Order orderEntry;
if (!orderDictionary.TryGetValue(order.OrderID, out orderEntry))
{
orderEntry = order;
orderEntry.OrderDetails = new List<OrderDetail>();
orderDictionary.Add(orderEntry.OrderID, orderEntry);
}
orderEntry.OrderDetails.Add(orderDetail);
return orderEntry;
},
splitOn: "OrderID")
.Distinct()
.ToList();
Console.WriteLine(list.Count);
FiddleHelper.WriteTable(list);
FiddleHelper.WriteTable(list.First().OrderDetails);
}
示例:查询多类型
可以使用Query方法执行原始SQL查询,并将结果映射到不同类型的列表。
string sql = "SELECT * FROM Invoice;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoices = new List<Invoice>();
using (var reader = connection.ExecuteReader(sql))
{
var storeInvoiceParser = reader.GetRowParser<StoreInvoice>();
var webInvoiceParser = reader.GetRowParser<WebInvoice>();
while (reader.Read())
{
Invoice invoice;
switch ((InvoiceKind) reader.GetInt32(reader.GetOrdinal("Kind")))
{
case InvoiceKind.StoreInvoice:
invoice = storeInvoiceParser(reader);
break;
case InvoiceKind.WebInvoice:
invoice = webInvoiceParser(reader);
break;
default:
throw new Exception(ExceptionMessage.GeneralException);
}
invoices.Add(invoice);
}
}
My.Result.Show(invoices);
}