SQL to LINQ: Transforming a Grouped Query with Left Join
This article provides a step-by-step guide to converting a SQL query into its equivalent LINQ expression. The example focuses on a query that performs a left join, grouping, and ordering. Let's break down the SQL query and its LINQ translation.
Original SQL Query:
SELECT A.StationNo,COUNT(A.StationNo)
FROM [Mesdatabase_6631].[dbo].[Work_Process] A
LEFT JOIN Base_Station B ON A.StationNo=B.StationNo
GROUP BY
A.StationNo,B.SortIndex
ORDER BY B.SortIndex
Equivalent LINQ Expression:
var result = from A in db.Work_Process
join B in db.Base_Station on A.StationNo equals B.StationNo into AB
from B in AB.DefaultIfEmpty()
group A by new { A.StationNo, B.SortIndex } into g
orderby g.Key.SortIndex
select new { StationNo = g.Key.StationNo, Count = g.Count() };
Explanation:
from A in db.Work_Process: This line represents theFROMclause in SQL, specifying that we are selecting data from theWork_Processtable and assigning it to the variableA.join B in db.Base_Station on A.StationNo equals B.StationNo into AB: This implements the left join. It joins theWork_Processtable (aliased asA) with theBase_Stationtable (aliased asB) based on theStationNocolumn. The result of the join is stored inAB.from B in AB.DefaultIfEmpty(): This handles the left join aspect. It retrieves all records from theWork_Processtable, even if there is no matching record in theBase_Stationtable. If a match is not found, a default value (null in this case) is returned.group A by new { A.StationNo, B.SortIndex } into g: This represents theGROUP BYclause, grouping the data byStationNoandSortIndex(columns from the joined tables). The grouped data is assigned to the variableg.orderby g.Key.SortIndex: This is theORDER BYclause, sorting the grouped data based on theSortIndexcolumn. Note thatg.Keyrefers to the object containing the group key values.select new { StationNo = g.Key.StationNo, Count = g.Count() }: This line specifies the data to be selected. For each group (g), it selects theStationNoand the count of elements in the group (g.Count()).
Key Points:
- The LINQ expression uses the
intokeyword to create a temporary variable (AB) to store the intermediate join results, enabling us to process the left join in a more concise way. - The
DefaultIfEmpty()method is used to include records from theWork_Processtable that do not have a match in theBase_Stationtable, maintaining the left join behavior. - The
group byclause is used to group the data by the desired columns, and theorderbyclause sorts the groups based on theSortIndexcolumn.
By understanding the conversion process and the corresponding elements in both SQL and LINQ, you can effectively translate SQL queries into LINQ expressions and leverage the powerful features of LINQ for querying and data manipulation.
原文地址: http://www.cveoy.top/t/topic/f2Rg 著作权归作者所有。请勿转载和采集!