LINQ多重连接性能优化

时间:2017-02-27 16:42:05

标签: c# sql-server performance linq

我需要检索订单记录列表,并且我必须为每个订单显示相同的视图:

  • 已发出多少发票( InvoiceCount
  • 发票所涵盖的总金额(已开票
  • 已开具发票已支付多少(付款

所有在同一网格视图上。

我认为这是业务管理软件的基本视图。

订单> 发票 =一对多

付款发票相关,并带有查找表 PaymentsToInvoices

GridView是页面服务器端,页面大小为50条记录。

我已经编写了以下LINQ,它工作正常,但我有一些疑问,就性能而言, 特别是如果这个查询最终用几个子查询翻译,这意味着每个请求有50 * 2个查询!

var orders = (from o in db.Orders
  join c in db.Customers on o.CustomerID equals c.CustomerID
  join os in db.OrderStatuses on o.OrderStatusID equals os.OrderStatusID
  join ps in db.PaymentStatuses on o.PaymentStatusID equals ps.PaymentStatusID
  join ec in db.EntryChannels on o.EntryChannelID equals ec.EntryChannelID

  orderby o.InsertDate descending
  where o.OrderStatusID == 2
  select new
  {
      o.OrderID,
      o.CustomerID,
      o.InsertDate,
      o.TotalPrice,
      o.Notes,
      c.FirstName,
      c.LastName,
      OrderStatus = os.Name,
      PaymentStatus = ps.Name,
      EntryChannel = ec.Name,
      InvoiceCount = (db.InvoiceDetails.Where(i => i.OrderID == o.OrderID).Select(s => s.InvoiceID).Distinct().Count()),
      Invoiced = (db.InvoiceDetails.Where(i => i.OrderID == o.OrderID).Select(s => s.TotalPrice).Sum()),
      Payed = (from py in db.Payments
               join pti in db.PaymentsToInvoices on py.PaymentID equals pti.PaymentID
               join inv in db.InvoiceDetails on pti.InvoiceID equals inv.InvoiceID
               where inv.OrderID==o.OrderID
               select new { py.PaymentID, py.Amount }).Distinct().Select(s=>s.Amount).Sum()
  });

您如何看待最后三个领域?他们能以某种方式得到改善吗?它们会导致性能杀手子查询吗?

0 个答案:

没有答案