[英]Convert this sql query to LINQ to Lambda Left Outer Join
我试图将此sql查询转换为Linq到lambda,但我没有成功,我只有表位置中与表requireddocuments上的ID匹配的记录,我也希望为null。 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();
使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.