Convert SQL containing multiple connections, count and left connection to linq
Given SQL query contains multiple connections (including left connections) and the aggregation of using the count and the count (distinct) function. The goal is to convert this query to its linq equivalent items for the data access layer of the application.
SQL query:
<code class="language-sql">SELECT DISTINCT c.Id, c.Title, COUNT(v.Id) AS 'Nb_V2', COUNT(DISTINCT v.IdUser) AS 'Nb_V1', r.cnt AS 'Nb_R' FROM TABLE_C c JOIN TABLE_V v on c.Id = v.Id LEFT JOIN ( SELECT Id, COUNT(*) AS cnt FROM TABLE_R GROUP BY Id ) r ON c.Id = r.Id WHERE c.IdUser = '1234' GROUP BY c.Id, c.Title, r.cnt</code>
A method that converts the SQL query to the linq query understanding is to use nested connections and anonymous types. However, converting the count and count (differentinct) function to the linq syntax may be challenging. Lambda expression:
You can use LAMBDA expressions to implement a more concise solution for linq conversion. By using Join ... selectmany to operate and group, you can write the query as follows:
Translation Guide:
In order to effectively convert the SQL query to linq, the following guidelines can be applied:
<code class="language-csharp">var ans2 = Table_C.Where(c => c.IdUser == "1234") .Join(Table_V, c => c.Id, v => v.Id, (c, v) => new { c, v }) .GroupJoin(Table_R.GroupBy(r => r.Id).Select(rg => new { Id = rg.Key, cnt = rg.Count() }), cv => cv.c.Id, r => r.Id, (cv, rj) => new { cv.c, cv.v, rj }) .SelectMany(cvrj => cvrj.rj.DefaultIfEmpty(), (cvrj, r) => new { cvrj.c, cvrj.v, r }) .GroupBy(cvr => new { cvr.c.Id, cvr.c.Title, cvr.r?.cnt }) //处理r可能为空的情况 .Select(cvrg => new { cvrg.Key.Title, Nb_V2 = cvrg.Count(), Nb_V1 = cvrg.Select(cvr => cvr.v.IdUser).Distinct().Count(), Nb_R = cvrg.Key.cnt });</code>
Unless the child chooses to quote the external column, it should be converted independently.
A single single operator and polymerization operator can be directly applied to the results of the linq query.Anonymous type is used to represent multiple columns.
r
In the GroupBy
AND Select
Clauses, ains this change. The Rest of the Explaanation Remains The Same , Providing A Clear and Accurate Translation Guide from SQL To Linq. The above is the detailed content of How to translate a complex SQL query with multiple joins, COUNT, and a left join into its LINQ equivalent?. For more information, please follow other related articles on the PHP Chinese website!