結(jié)果多映射

2022-04-21 09:44 更新

描述

可以使用擴(kuò)展方法執(zhí)行查詢并將結(jié)果映射到具有關(guān)系的強(qiáng)類型列表。

關(guān)系可以是:

  • 一對(duì)一
  • 一對(duì)多

這些擴(kuò)展方法可以從IDbConnection類型的任意對(duì)象中調(diào)用。

案例 - 查詢多映射(一對(duì)一)

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();
}

案例 - 查詢多映射(一對(duì)多)

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();
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)