可以使用擴(kuò)展方法執(zhí)行查詢并將結(jié)果映射到具有關(guān)系的強(qiáng)類型列表。
關(guān)系可以是:
這些擴(kuò)展方法可以從IDbConnection類型的任意對(duì)象中調(diào)用。
Query方法可以執(zhí)行查詢并將結(jié)果映射到具有一對(duì)一關(guān)系的強(qiáng)類型列表。
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();
}
Query方法可以執(zhí)行查詢并將結(jié)果映射到具有一對(duì)多關(guān)系的強(qiáng)類型列表。
string sql = "SELECT * FROM Invoice AS A INNER JOIN InvoiceItem AS B ON A.InvoiceID = B.InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
var invoiceDictionary = new Dictionary<int, Invoice>();
var invoices = connection.Query<Invoice, InvoiceItem, Invoice>(
sql,
(invoice, invoiceItem) =>
{
Invoice invoiceEntry;
if (!invoiceDictionary.TryGetValue(invoice.InvoiceID, out invoiceEntry))
{
invoiceEntry = invoice;
invoiceEntry.Items = new List<InvoiceItem>();
invoiceDictionary.Add(invoiceEntry.InvoiceID, invoiceEntry);
}
invoiceEntry.Items.Add(invoiceItem);
return invoiceEntry;
},
splitOn: "InvoiceID")
.Distinct()
.ToList();
}
更多建議: