简体   繁体   中英

Entity Framework 6 Using Lambda GroupBy on a joined table

I have two tables, Drivers and ViewDrivers that I have joined together using the following lambda expression in Entity Framework 6.

var inAppDriverList = context.ViewDrivers
.Select(dv => new { dv.TerminalCode, dv.EmployeeId })
.Join(
          context.Drivers,
          d => d.EmployeeId,
          dv => dv.EmployeeId,
          (d, dv) => new { d, dv }
      ))
.OrderBy(dv => dv.TerminalCode)
.GroupBy(dv => dv.TerminalCode
.ToList();

It does give me the data that I am expecting to get, but I when I try to Sort and Group the list by the TerminalCode using GroupBy and OrderBy , I cannot get it to work correctly. I have tried everything I can think of, with no luck.

I am only having this issue when I am trying to sort a joined table so I am guessing there is something small that I am missing. I would greatly appreciate any help in getting those statements to Group and Sort by the TerminalCode field.

The result of your Join will be a sequence of the anonymous class that you created with

(d, dv) => new { d, dv }

So when you try to order and group you need a lambda like

x => x.dv.TerminalCode

That or specify the values of dv in the anonymous class

(d, dv) => new { d, dv.TerminalCode, dv.EmployeeId  }

With that option you then wouldn't need the Select before the Join . Additionally if you don't need all the columns in Drivers you can also specify them as well thus reducing the amount of data that your query has to return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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