将 SQL 查询重写为 LINQ

本文关键字:LINQ 重写 查询 SQL | 更新日期: 2023-09-27 18:34:35

有人可以帮我把这段代码重写成LINQ吗?

SELECT UP.ProjectId 
FROM UserProjects UP
INNER JOIN Projects P ON UP.ProjectId = P.ProjectId
WHERE P.Status = 1 
GROUP BY  UP.ProjectId 
HAVING COUNT(CASE WHEN UP.UserId = 1 THEN 1 END) = 0
The HAVING clause filters out projects related to user with UserId = 1.

将 SQL 查询重写为 LINQ

试试这个:

var result=(from up in DbContext.UserProjects 
            join p in DbContext.Products on up.ProjectId equals p.ProjectId 
            where p.Status == 1 && up.userid==1
            group up by up.ProjectId into gps
            select gps.FirstOrDefault().ProjectId ).ToList();