简体   繁体   English

LINQ中的左联接和按列区分

[英]Left Join and Distinct by Column in LINQ

I am having two relations: Users and UserProjects . 我有两个关系: UsersUserProjects

I want to check which user is already in project. 我想检查哪个用户已经在项目中。 So far it`s like this: 到目前为止,它是这样的:

 var usrs = (from users in context.Users
                        join userProj in context.UserProjects
                        on users.UserId equals userProj.UserId into gj
                        from subuserProject in gj.DefaultIfEmpty()
                        select new ProjectUsersDTO
                        {
                            UserName = users.Name,
                            Rate = users.RatePerHour,
                            UserId = users.UserId,
                            alreadyInProject = subuserProject == null || subuserProject.ProjectId != projectId ? false : true
                        })
                      .ToList();

The problem is I want to get them distinct. 问题是我想让它们与众不同。 Right now I am getting one user with alreadyInProject == true and alreadyInProject == false . 现在,我正在使用一位用户alreadyInProject == truealreadyInProject == false

If you are checking for some particular project, then you don't need to join all projects - simply filter user projects before joining: 如果要检查某个特定项目,则无需加入所有项目-只需在加入之前过滤用户项目:

from user in context.Users
join userProj in context.UserProjects.Where(up => up.ProjectId == projectId)
    on user.UserId equals userProj.UserId into g
from subuserProject in g.DefaultIfEmpty()
select new ProjectUsersDTO {
    UserName = user.Name,
    Rate = user.RatePerHour,
    UserId = user.UserId,
    alreadyInProject = (subuserProject != null)
}

Generated query will look like 生成的查询看起来像

SELECT
  [Extent1].[UserId] AS [UserId],
  [Extent1].[Name] AS [Name],
  [Extent1].[RatePerHour] AS [RatePerHour],
  CASE WHEN ([Extent2].[UserProjectId] IS NOT NULL) 
       THEN cast(1 as bit)
       ELSE cast(0 as bit)
  END AS [C1]
  FROM  [dbo].[Users] AS [Extent1]
  LEFT OUTER JOIN [dbo].[UserProjects] AS [Extent2] 
     ON ([Extent2].[ProjectId] = @p__linq__0) AND ([Extent1].[UserId] = [Extent2].[UserId])

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

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