在处理将我的雇主内部系统从 asp 迁移到 asp.net MVC 之前,我使用典型的发票系统作为开发 MVC 和 ViewModel 知识的测试。
我知道 ViewModels 是在视图中显示信息的推荐方式 - 所以我希望得到一些帮助“扁平化”以下视图模型:
表:发票、发票项目、付款、付款发票
Invoice 和 InvoiceItem 链接在一起,Payment(记录总付款)和 PaymentInvoice(列出 Payment 涵盖的发票)也链接在一起。
我想要一个 ViewModel 向我展示:
InvoiceId CustomerName 总发票(数量 X 单价加增值税) AmountAllocated(来自 PaymentInvoice 表) 未结清(TotalofInvoice - AmountAllocated)
所以我认为我的 ViewModel 应该是:
public class InvoiceViewModel
{
public Int InvoiceId { get; set; }
public string CustomerName { get; set; }
public decimal TotalofInvoice { get; set; }
public decimal AmountAllocated { get; set; }
public decimal Outstanding { get; set; }
}
我的域模型是:
public class Invoice
{
public int InvoiceId { get; set; }
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string Email { get; set; }
public DateTime InvDate { get; set; }
public IList<InvoiceItem> InvoiceItems { get; set; }
}
public class InvoiceItem
{
public int InvoiceItemId { get; set; }
public int InvoiceId { get; set; }
public string Item { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal VAT { get; set; }
public virtual Invoice Invoice { get; set; }
// calculated fields
public decimal Total
{
get { return Quantity * UnitPrice; }
}
public decimal VATAmount
{
get { return TotalPlusVAT - Total; }
}
public decimal TotalPlusVAT
{
get { return Total * (1 + VAT / 100); }
}
}
public class Payment
{
public int PaymentId { get; set; }
public int CustomerId { get; set; }
public DateTime DateReceived { get; set; }
public decimal TotalReceived { get; set; }
public IList<PaymentInvoice> PaymentInvoices { get; set; }
}
public class PaymentInvoice
{
public int PaymentInvoiceId { get; set; }
public int PaymentId { get; set; }
public decimal AmountAllocated { get; set; }
public int InvoiceId { get; set; }
public virtual Payment Payment { get; set; }
}
我的问题是如何将 Payment 和 PaymentInvoice 表链接到 Invoice 和 InvoiceItem 表,因此我可以在我的控制器中使用 LINQ 查询来使用“扁平数据”填充视图模型。
我也迷失了 LINQ 查询 - 在 LinqPad 中我有:
from c in Invoices
join i in InvoiceItems on c.InvoiceId equals i.InvoiceId
join pi in PaymentInvoices on c.InvoiceId equals pi.InvoiceId
select new {...into ViewModel????...}
...但不知道在那之后去哪里。
编辑- 我最接近的是 Sql 这样做是:
SELECT Invoices.InvoiceId,
Invoices.CustomerName,
(SUM(InvoiceItems.Quantity * InvoiceItems.UnitPrice)) AS TotalOfInvoice,
(SELECT SUM(AmountAllocated) AS Expr1
FROM PaymentInvoices
WHERE (InvoiceId = Invoices.InvoiceId)) AS AmountAllocated,
SUM(InvoiceItems.Quantity * InvoiceItems.UnitPrice)
- (SELECT SUM(AmountAllocated) AS Expr1
FROM PaymentInvoices
WHERE (InvoiceId = Invoices.InvoiceId)) AS Outstanding
FROM Invoices LEFT OUTER JOIN
InvoiceItems ON Invoices.InvoiceId = InvoiceItems.InvoiceId
GROUP BY Invoices.InvoiceId, Invoices.CustomerName
谢谢,
标记