如何在Entity框架中创建多个Left Join

时间:2014-08-08 08:37:27

标签: sql entity-framework entity-framework-4

我有SQL查询:

FROM tbl_UploadFile AS AllFiles 
LEFT JOIN tbl_FirstFile AS firstFiles ON AllFiles.Guid=firstFiles.[FileId]
LEFT JOIN tbl_SecondFile AS secondFiles ON AllFiles.Guid=secondFiles.[FileId]
LEFT JOIN tbl_ThirdFile AS thirdFiles ON AllFiles.Guid=thirdFiles.[FileId]
WHERE firstFiles.[FileId] is NULL AND secondFiles.[FileId] is NULL AND thirdFiles.[FileId] is NULL; 

此查询从tbl_UploadFile返回guid,如果此guid不在tbl_FirstFile,tbl_SecondFile和tbl_ThirdFile上使用。 工作正常。

我尝试在Entity Framework上编写(使用GroupJoin),但我只能为tbl_FirstFile创建GroupJoin:

 var unlinkedFiles = context
    .Set<DbUploadFile>()
    .GroupJoin(
    context.Set<DbFirstFile>(),
    file => file.Guid,
    clFile => clFile.FileId,
    (file, files) => new
    {enter code here
    FileGuid = file.Guid,
    Children = files.Count()
    })
    .Where(x => x.Children == 0)
    .ToList();

如何为所有表写多次GroupJoin?

1 个答案:

答案 0 :(得分:4)

我不确定你的桌名。但你可以这样做:

var result= (
        from AllFiles in context.tbl_UploadFile
        from firstFiles in context.tbl_FirstFile
            .Where(w=>AllFiles.Guid=w.FileId).DefaultIfEmpty()
        from secondFiles in context.tbl_SecondFile
            .Where(w=>AllFiles.Guid=w.FileId).DefaultIfEmpty()
        from thirdFiles in tbl_ThirdFile
            .Where(w=>AllFiles.Guid=w.FileId).DefaultIfEmpty()
        where firstFiles.FileId== null
        where secondFiles.FileId == null  
        where thirdFiles.FileId == null
        select AllFiles
    ).ToList();

比我认为的GroupJoin更清洁