我试图将这个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
LAMBDA
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();
答案 0 :(得分: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);