我有加入此查询。这给了我一个内在的连接。我要完成的是左联接。
我尝试使用DefaultIfEmpty(),但无法正常工作。也许我把它放在查询的错误部分。

谁能指出我使用DefaultIfEmpty()的正确方法吗?

以下是我当前的查询:

var AppList = (de.ComputerUserApplication)
                    .Where(CUA => CUA.EmployeeID == employeeID)
                    .DefaultIfEmpty()
                    .Join(de.ApplicationTypeMasters,
                        CUA => CUA.RecordType,
                        ATM => ATM.Code,
                        (CUA, ATM) => new ApplicationModel
                        {
                            ApplicationNo = CUA.ApplicationNo,
                            ApplicationCode = CUA.RecordType,
                            ApplicationTypeCode = "",
                            ApplicationName = ATM.Title + " - " + CUA.Description,
                            Status = CUA.Status
                        });


另外,我不确定我是否有正确的查询。如果可以的话,以下是我的原始查询:

select Cua_ApplicationNo, Cua_Type_Rec, ATM_ApplicationTitle, Cua_Status  from ComputerUserApplication
left join ApplicationTypeMaster
    on Cua_Type_Rec = ATM_ApplicationCode
        where Cua_EmployeeID = 'someID'

最佳答案

您需要使用GroupJoin for an outer join;假设有0或1个匹配的ApplicationTypeMaster行,这将起作用;如果更多,则需要先执行DefaultIfEmpty,然后再执行SelectMany

de.ComputerUserApplication
  .Where(x => x.EmployeeID == employeeID)
  .GroupJoin(
      de.ApplicationTypeMasters,
      CUA => CUA.RecordType,
      ATM => ATM.Code,
      (CUA, ATM) => new ApplicationModel
      {
          ApplicationNo = CUA.ApplicationNo,
          ApplicationCode = CUA.RecordType,
          ApplicationTypeCode = "",
          ApplicationName = ATM.SingleOrDefault()?.Title + " - " + CUA.Description,
          Status = CUA.Status
      }
  );


如果您不知道匹配的行数,那么SelectMany将为您提供与SQL等效的结果:

de.ComputerUserApplication
  .Where(x => x.EmployeeID == employeeID)
  .GroupJoin(
      de.ApplicationTypeMasters,
      CUA => CUA.RecordType,
      ATM => ATM.Code,
      (x, y) => new { CUA = x, ATMs = y.DefaultIfEmpty() }
  ).SelectMany(x => x.ATMs.Select(ATM => new ApplicationModel
      {
         ApplicationNo = x.CUA.ApplicationNo,
         ApplicationCode = x.CUA.RecordType,
         ApplicationTypeCode = "",
         ApplicationName = ATM?.Title + " - " + x.CUA.Description,
         Status = x.CUA.Status
      }
  );


顺便说一句,这是我更喜欢查询语法的少数情况之一(使用SelectMany时没有所有杂音):

  from CUA in de.ComputerUserApplication
  join x in de.ApplicationTypeMasters on CUA.RecordType equals x.Code into g
  from ATM in g.DefaultIfEmpty()
  select new ApplicationModel()
  {
     ApplicationNo = CUA.ApplicationNo,
     ApplicationCode = CUA.RecordType,
     ApplicationTypeCode = "",
     ApplicationName = ATM?.Title + " - " + CUA.Description,
     Status = CUA.Status
   };

09-06 23:51