Dapper 将子查询值映射到 属性

Dapper map subquery value to property

我正在使用 Dapper 来获取和映射数据。我有以下查询和相关 class.

SELECT pinv.* , sp.SupplierId,sp.SupplierName,sp.Contact1,sp.SupplierAddress,ac.AccountId,ac.AccountName, 
(Select Count(*) from ReturnInvoices rinv Where rinv.InvoiceId = pinv.PurchaseInvoiceId) as ReturnInvoicesCount  
FROM PurchaseInvoices pinv  
LEFT JOIN Suppliers sp ON sp.SupplierId = pinv.SupplierId  
LEFT JOIN Accounts ac on ac.AccountId = pinv.AccountId  

还有 class.

public class PurchaseInvoice
{
    public int PurchaseInvoiceId { get; set; }
    public int PurchaseOrderId { get; set; }
    public string PurchaseInvoiceType { get; set; }
    public int SupplierId { get; set; }
    public int AccountId { get; set; }
    public int ReceiptNumber { get; set; }
    public int ReturnInvoicesCount { get; set; }  // to map ReturnInvoiceCount by SubQuery
    public DateTime PromisedDate { get; set; }
    public DateTime InvoiceDate { get; set; }
    public decimal InvoiceQuantity { get; set; }
    public decimal Discount { get; set; }
    public decimal Tax { get; set; }
    public decimal ShippingCharges { get; set; }
    public decimal Surcharge { get; set; }
    public string PaymentMode { get; set; }
    public decimal SubTotal { get; set; }
    public decimal TotalPayment { get; set; }
    public decimal AmountPaid { get; set; }
    public decimal AmountRemaining { get; set; }
    public string Comments { get; set; }
    public string Status { get; set; }
    public DateTime UpdatedDate { get; set; }

    public Supplier Supplier { get; set; }
    public ProductReceived ProductReceived { get; set; }
    public Account Account { get; set; }
}  

我不会分享其他 classes,因为它们不相关。现在,如果我 运行 以上查询,我会得到完美的结果。获取结果后,dapper returns 所有数据都很好,但 ReturnInvoicesCount 未映射 (或者 idk 其他问题)。这就是我使用 dapper 的方式。

using (SqlConnection connection = new SqlConnection(_conString))
{
    var query = QueryHelper.GetPurchaseInvoicesQuery(start, end, simpleSearchText, searchTokensList);
    // ignore above line, just getting query with parameters etc

    var data = await connection.QueryAsync<PurchaseInvoice, Supplier, Account>(query.Query,
        query.queryParams, splitOn: "SupplierId,AccountId");

    return data;
}  

正如我所说,除了字段 ReturnInvoicesCount 为 0 之外,我得到了正确的映射结果。在服务器上可以看到 ReturnInvoiceCount 有一个值。

您在 SupplierId(映射到 Supplier)和 AccountId(映射到 Account)上进行了拆分。问题是 ReturnInvoicesCount 位于错误的列位置,无法正确映射。目前,您告诉 dapper ReturnInvoicesCount 属于 Account。

由于 ReturnInvoicesCount 属于 PurchaseInvoice 你必须在 SupplierId 之前移动它。