简体   繁体   中英

How to Perform a Join Operation with a Group by In EF CORE

I have two tables Clients and ClientEvaluations, those tables are connected through a foreign key. Each ClientEvaluation has FK to a single Client Entity.

Now i need to query all clients with their last evaluation, no more than one valuation per client. Note that each evaluation has a date.

This code here achieves that in SQL.

SELECT C.Id, MAX(E.EvaluationDate) FROM [dbo].[Clients] as C

JOIN [dbo].[ClientEvaluations] AS E ON E.ClientId = C.Id

GROUP BY C.Id

I have also tried this but the problem with what I'm trying to achieve is that i need to get back from this query the Client entity properties as well.

var lastEvaluations = _db.ClientEvaluations.GroupBy(x => x.ClientId, (x, y) => new { ClientId = x, EvaluationDate = y.Max(z => z.EvaluationDate), }).ToList();

But the query here of course only returns the ClientId and the date, how can i include the whole client entity?

I hope you have configured _dbContext correctly . Then you can use include to do the join operation.

var results = _dbcontext
                .Clients
                .Include(x => x.ClientEvaluations) //join
                .GroupBy(y => y.Id) // group by
                .Select(z => new 
                   {
                       Id = z.Key.Value,
                       Max = z.Max(x => x.EvaluationDate),
                   }).ToList();

Or

var results =   from c in _dbcontext.Clients
                join e in _dbcontext.ClientEvaluations
                on c.Id equals e.ClientId
                group c by c.Id into cg
                select new
                {
                    Id = Id = cg.FirstOrDefault().Id,
                    Max = cg.Max(x => x.EvaluationDate),
                }).ToList();

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