How to create multiple Left Join in Entity framework

笑着哭i 提交于 2019-12-11 07:49:01

问题


I have sql query:

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; 

This query return guid from tbl_UploadFile, if this guid doen't use on tbl_FirstFile, tbl_SecondFile and tbl_ThirdFile. It is work fine.

I try to write on Entity Framework (using GroupJoin), but I can make GroupJoin only for tbl_FirstFile:

 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();

How write multiples GroupJoin for all tables?


回答1:


I am not sure about your table names. But you could do something like this:

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();

It is much cleaner then doing a GroupJoin I think



来源:https://stackoverflow.com/questions/25199228/how-to-create-multiple-left-join-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!