简体   繁体   中英

Conversion of SQL group by to Entity Framework Lambda expression

I have 3 tables A which has an ID and other fields, B which has an ID, and C has a many to many relation for the ID's in A and B

I made a query that gets the results that I need

select result.*
from 
    (SELECT max(A.AID) as AID
    FROM A, C
    where A.AID = C.AID
    group by C.BID) as x, A as result
where result.AID = x.AID

and I want to convert it to a lambda expression in entity framework. But currently the query is not efficient enough. How would I make the lamda expression in EF and also make it more efficient?

If you first order your results descending by the ID you want the max of, and then GroupBy that ID in the related table, then Select the First from each grouping you should get the results you need.

var groupedResults = tempContext.A.OrderByDescending(a => a.AID
).GroupBy(group => group.C.AID).Select(group => group.FirstOrDefault());

This should return you an IQueryable of the A entity that you can then continue to modify with additional clauses if needed.

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