我正在使用Dapper Multi Mapping来返回发票集合。每张发票都包含一组InvoiceItems。以下是模型。
public class InvoiceModel
{
public int InvoiceId { get; set; }
public string CustomerName { get; set; }
public List<InvoiceItemModel> InvoiceItems { get; set; }
}
public class InvoiceItemModel
{
public int InvoiceItemId { get; set; }
public int InvoiceId { get; set; }
public string ItemName { get; set; }
public int Quantity { get; set; }
}
我发现如果我放置代码来获取数据并直接在控制器中映射对象,那么一切正常。但是,我想将此代码放入从控制器调用的服务中。当我将代码放在服务中时,代码不起作用。实际上,我甚至无法在作为服务一部分的方法中使用lambda扩展Distinct()
或ToList()
。
此代码有效 - 请注意它在API控制器中的正确性
public List<InvoiceModel> GetInvoiceTest(int invoiceId)
{
using (IDbConnection db = new System.Data.SqlClient.SqlConnection(SqlDataAccess.LoadConnectionString("InvoiceDb")))
{
try
{
string sql = @"SELECT
Invoice.InvoiceId,
Invoice.Customer AS CustomerName,
InvoiceItem.InvoiceItemId,
InvoiceItem.InvoiceId,
InvoiceItem.[Name] AS ItemName,
InvoiceItem.Quantity
FROM Invoice
LEFT JOIN InvoiceItem ON Invoice.InvoiceId = InvoiceItem.InvoiceId
WHERE Invoice.InvoiceId = " + invoiceId;
var invoiceDictionary = new Dictionary<int, InvoiceModel>();
var invoices = db.Query<InvoiceModel, InvoiceItemModel, InvoiceModel>(
sql,
(invoiceModel, invoiceItemModel) =>
{
InvoiceModel invoiceEntry;
if (!invoiceDictionary.TryGetValue(invoiceModel.InvoiceId, out invoiceEntry))
{
invoiceEntry = invoiceModel;
invoiceEntry.InvoiceItems = new List<InvoiceItemModel>();
invoiceDictionary.Add(invoiceEntry.InvoiceId, invoiceEntry);
}
invoiceEntry.InvoiceItems.Add(invoiceItemModel);
return invoiceEntry;
},
splitOn: "InvoiceItemId").Distinct().ToList();
return invoices;
}
catch (Exception ex)
{
Log.Error("", "Get Invoice Error", new { InvoiceId = invoiceId }, ex);
throw new Exception("Error occured while trying to obtain Invoice", ex);
}
}
}
但是,如果我将相同的代码放在服务类中包含的静态方法中,我发现我无法使用.Distinct().ToList();
。我发现我可以将扩展名更改为.AsList();
,但结果会重复出现。
这是服务中的方法。
public static List<InvoiceModel> GetInvoices(int invoiceId)
{
using (...)
{
// Same code as above starting with the using statement
...
//splitOn: "InvoiceItemId").Distinct().ToList(); // Unavailable
splitOn: "InvoiceItemId").AsList(); // Only option available
}
}
是否与static
的服务方法有关?
注意:我为帖子的长度道歉。我尝试尽可能多地配对它,但我觉得最好列出模型。
答案 0 :(得分:0)
尝试以下方法
var invoices = db.QueryAsync<InvoiceModel, InvoiceItemModel, InvoiceModel>(
sql,
(invoiceModel, invoiceItemModel) =>
{
InvoiceModel invoiceEntry;
if (!invoiceDictionary.TryGetValue(invoiceModel.InvoiceId, out invoiceEntry))
{
invoiceEntry = invoiceModel;
invoiceEntry.InvoiceItems = new List<InvoiceItemModel>();
invoiceDictionary.Add(invoiceEntry.InvoiceId, invoiceEntry);
}
invoiceEntry.InvoiceItems.Add(invoiceItemModel);
return invoiceEntry;
},
null,
null,
true,
splitOn: "InvoiceItemId",
999)
.Result
.Distinct()
.ToList();
谢谢