在MVC中使用平台

时间:2017-09-22 22:19:40

标签: asp.net asp.net-mvc linq

如果我有一个包含多个表的模型,并且我将这些表一起连接到我的控制器类中的平面表中,如何让视图能够访问平面表?

例如,假设我的模型中有三个表(客户,订单,发票)。 订单通过外键(CustomerID)链接到客户,发票通过外键(OrderID)链接到订单。

为了在一个平面表中看到所有这些(列出所有客户,即使他们没有订单,列出所有订单,即使他们没有发票),我也有以下匿名类型:

var FlatTable = (from a in customers
let CustomerID = a.ID
join b in orders on a.ID equals b.CustomerID into ab
from b in ab.DefaultIfEmpty()
let OrderID = b.ID
join c in invoices on b.ID equals c.InvoiceID into ac
from c in ac.DefaultIfEmpty()
let InvoiceID = c.ID
select new {a.CustomerName, CustomerID, OrderID, b.ProductDescription, InvoiceID, c.InvoiceAmount});

return View(FlatTable.ToList());

然后在我的视图中(基于我的模型),我如何能够访问FlatTable。

1 个答案:

答案 0 :(得分:0)

IList<ViewModel> model = (from a in customers
join b in orders on a.ID equals b.CustomerID into ab
from b in ab.DefaultIfEmpty()
join c in invoices on b.ID equals c.InvoiceID into ac
from c in ac.DefaultIfEmpty()
select new ViewModel() {CustomerName = a.CustomerName, CustomerID = a.ID, OrderID = b.ID, ProductDescription = b.ProductDescription, InvoiceID = c.ID, InvoiceMaount = c.InvoiceAmount}).ToList();