简体   繁体   English

将SQL组转换为Entity Framework Lambda表达式

[英]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 我有3个表A,其中有ID和其他字段,B有ID,C对A和B中的ID有多对多的关系

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. 我想将它转换为实体框架中的lambda表达式。 But currently the query is not efficient enough. 但目前查询效率不高。 How would I make the lamda expression in EF and also make it more efficient? 我如何在EF中制作lamda表达式并使其更高效?

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. 如果您首先按照您想要的最大ID,然后在相关表中GroupBy该ID下降结果,那么从每个分组中选择First,您应该得到所需的结果。

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. 这应该返回A实体的IQueryable,然后您可以根据需要继续使用其他子句进行修改。

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

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