0

我试图将此 sql 查询转换为 Linq 到 lambda,但我没有成功我只有在表中与表中的 id 匹配的记录 requireddocuments 我也想要空值。sql 查询工作正常,但 lambda 不

SQL 查询。

  SELECT Document, Place, Record
   FROM RequiredApplicationDocuments LEFT OUTER JOIN Places ON
     RequiredApplicationDocuments.Id = Places.RequiredApplicationDocumentId
       WHERE Places.SecondPlaceId = 4 OR Places.SecondPlaceId IS NULL

拉姆达

Database.RequiredApplicationDocuments.Join(Database.Placess, 
            ra => ra.Id, fa => fa.RequiredApplicationDocumentId, (fa, ra) =>
            new {Places = fa, RequiredApplicationDocument = ra}).DefaultIfEmpty().toList().Select(fa => new Places
                           {
                  FileName = fa.RequiredApplicationDocument.FileName,
                  LoanApplicationId = fa.RequiredApplicationDocument.LoanApplicationId,
                  Name = fa.RequiredApplicationDocument.Name,
                  RequiredApplicationDocument = fa.RequiredApplicationDocument.RequiredApplicationDocument,
                  Id = fa.Places.Id,
                  CreationDate = fa.RequiredApplicationDocument.CreationDate,
                  Contents = fa.RequiredApplicationDocument.Contents,
                  RequiredApplicationDocumentId = fa.RequiredApplicationDocument.RequiredApplicationDocumentId,
                  LoanApplication = fa.RequiredApplicationDocument.LoanApplication,
                  Type = fa.RequiredApplicationDocument.Type 
            }).AsQueryable();
4

1 回答 1

4

使用 GroupJoin

这更针对您的 SQL,而不是针对您的 LINQ

        var res = RequiredApplicationDocuments.GroupJoin(Places,
            p => p.Id,
            d => d.RequiredApplicationDocumentId,
            (d, places) => new
            {
                Document = d,

                Place = places.Where(p => p.SecondPlaceId == 4).FirstOrDefault(),

                // if don't want to exclude documents with "non-4" places only, 
                // remove this and last where clause
                // but this is what your SQL does
                HasNoPlaces = places.Count() == 0 

            }).Where(r => r.HasNoPlaces || r.Place != null);
于 2012-12-13T22:38:30.743 回答