C# LINQ到实体左连接单个聚合结果

C# LINQ到实体左连接单个聚合结果,c#,sql,linq-to-entities,C#,Sql,Linq To Entities,低优先级问题,因为我已经有了解决方案,但我认为有更好的方法。我尝试返回一个结果,就像下面的SQL查询: 选择COUNT*IsAuthenticated,COUNTUTP.HashedPassword istempsword 来自[EnterpriseDB].[dbo].[UniversalCurrentPassword]作为UCP 将[EnterpriseDB].[dbo].[UniversalTempPassword]作为UTP左加入 关于UCP.UniversalId=UTP.Univers

低优先级问题,因为我已经有了解决方案,但我认为有更好的方法。我尝试返回一个结果,就像下面的SQL查询:

选择COUNT*IsAuthenticated,COUNTUTP.HashedPassword istempsword 来自[EnterpriseDB].[dbo].[UniversalCurrentPassword]作为UCP 将[EnterpriseDB].[dbo].[UniversalTempPassword]作为UTP左加入 关于UCP.UniversalId=UTP.UniversalId 其中UCP.UniversalId=00000 和UCP.HashedPassword='some\u password' 或UTP.HashedPassword='some_password' 以下是我已经得到的:

//如果不匹配,则返回null //如果使用临时密码,则返回true //如果为当前密码,则返回false 布尔?查询= 来自context.UniversalCurrentPasswords中的密码 在context.UniversalTempPasswords中加入TempPassword on Password.UniversalId等于TempPassword.UniversalId 其中Password.UniversalId==longId &&Password.HashedPassword==pwd ||Password.UniversalMaster.UniversalTempPassword.HashedPassword==pwd 选择TempPassword.HashedPassword==null?true:false.FirstOrDefault; 你认为有什么更好的方法吗

试试这个:

bool? query =   
     (from Password in context.UniversalCurrentPasswords 
      join TempPassword in context.UniversalTempPasswords 
      on Password.UniversalId equals TempPassword.UniversalId into tp
      from TempPassword in tp.DefaultIfEmpty()
      where Password.UniversalId == longId 
          && (Password.HashedPassword == pwd 
          || Password.UniversalMaster.UniversalTempPassword.HashedPassword == pwd) 
      select (TempPassword == null ? null as bool? : 
              TempPassword.HashedPassword == null ? (bool?)true : (bool?)false)
     ).FirstOrDefault();

select子句中条件表达式的类型为bool,而不是bool?,bool的默认值为false,因此如果没有记录,查询变量将为false;它永远不能为空。