简体   繁体   English

如何在Linq语句的多重联接中包含所有字段?

[英]How to include all fields in a multiple join into Linq statement?

var largeset =
from invs in context.Invoices
join lines in context.InvoiceLines on invs.InvoiceId equals lines.InvoiceId
join tracks in context.Tracks on lines.TrackId equals tracks.TrackId into grp
select new
          {
              Invoice = invs,
              Detail = grp
          };

In the above join into statement, Detail is a list but it only contains Invoice and Track columns. 在上面的join into语句中,Detail是一个列表,但仅包含Invoice和Track列。 I want to be able to get columns from InvoiceLine as well. 我也希望能够从InvoiceLine获取列。

Thanks in advance. 提前致谢。

If you want to get the line info list for the invoice, you need to move the into to the first join and perform the other join inside the outer select . 如果你想获得的行信息列表发票,你需要移动into的第一join并执行其他join内外部select

Something like this: 像这样:

var largeset =
    from inv in context.Invoices
    join line in context.InvoiceLines on inv.InvoiceId equals line.InvoiceId into lines
    select new
    {
        Invoice = inv,
        Lines =
            from line in lines
            join track in context.Tracks on line.TrackId equals track.TrackId
            select new { Line = line, Track = track }
    };

As an alternative to Ivan's solution which should yield better performance. 作为Ivan解决方案的替代方案,它应产生更好的性能。

var largeset =
  from invs in context.Invoices
  join lines in context.InvoiceLines on invs.InvoiceId equals lines.InvoiceId
  join tracks in context.Tracks on lines.TrackId equals tracks.TrackId
  group new { invs, lines, tracks }
  by new
  {
      invs.InvoiceId,
      invs.InvoiceDate,
      invs.CustomerId,
      invs.Customer.LastName,
      invs.Customer.FirstName
  } into grp
  select new
  {
      InvoiceId = grp.Key.InvoiceId,
      InvoiceDate = grp.Key.InvoiceDate,
      CustomerId = grp.Key.CustomerId,
      CustomerLastName = grp.Key.LastName,
      CustomerFirstName = grp.Key.FirstName,
      CustomerFullName = grp.Key.LastName + ", " + grp.Key.FirstName,
      TotalQty = grp.Sum(l => l.lines.Quantity),
      TotalPrice = grp.Sum(l => l.lines.UnitPrice),
      Tracks = grp.Select(t => t.tracks)
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM