简体   繁体   中英

Selecting max in linq query or rewriting to method chain syntax

I managed to turn this SQL query:

SELECT c.carId, c.Codename, count(c.CarId) as [CarCount],
  FROM [DbEfTesting].[dbo].[Cars] c
  left join Accessories a on c.CarId = a.CarId
  left join CarsPeople cp on cp.CarId = c.CarId
  left join People p on cp.PersonId = p.PersonId
  group by c.CarId, c.Codename

into a LINQ query:

var x = from c in _context.Cars
    join a in _context.Accessories on c.CarId equals a.Car.CarId
    join j in _context.CarsPeople on c.CarId equals j.CarId
    join p in _context.People on j.PersonId equals p.PersonId
    group c by new { c.CarId, c.Codename } into g
    select new VMCarAggregate()
    {
        CarId = g.Key.CarId,
        Codename = g.Key.Codename,
        CarCount = g.Count()
    };

But now I'm lost trying to include a max value eg the SQL:

SELECT c.carId, c.Codename, count(c.CarId) as [CarCount], max(a.AccessoryId) ...

I googled it and found lots of answers for method syntax. If I were using method chain syntax, I know I could do something like this:

_context.Accessories.Max(a => a.AccessoryId);

but I can't figure out how to do the group by in method chain syntax so either:

How can I convert that query to method syntax?

or

How can I inject a select on the max a.AccessoryId in the LINQ query format?

Try the below code once:

var x = from c in _context.Cars
                    join a in _context.Accessories equals a.Car.CarId
                    join j in _context.CarsPeople on c.CarId equals j.CarId
                    join p in _context.People on j.PersonId equals p.PersonId
                    group new { c.CarId, c.Codename, a.AccesoryId } by new { c.CarId, c.Codename } into g
                    select new
                    {
                        CarId = g.Key.CarId,
                        Codename = g.Key.Codename,
                        CarCount = g.Count(),
                        MaxAccesory = g.Max(z => z.AccesoryId)
                    };

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