Linq中的简单左连接未按预期工作

时间:2015-11-14 06:47:59

标签: c# linq left-join

我想将以下查询转换为Linq

select m.Id,m.MenuName,mr.CanAdd,mr.CanDelete,mr.CanEdit
from Menu m
left join MenuRole mr on m.Id=mr.MenuID
and mr.DesignationID=1 where m.ParentID<>0

预期结果

enter image description here

我尝试过以下但未获得所需的结果

var test = (from m in _db.Menus
                   join mr in _db.MenuRoles on m.Id equals mr.MenuID  into t
                   from rt in t.Where(x=>x.Menu.ParentID!=0).DefaultIfEmpty()
                   where rt.DesignationID==1
                   orderby m.Id 
                   select new MenuVM
                   {
                       CanAdd=rt.CanAdd==null?false:true,
                       CanEdit=rt.CanEdit==null?false:true,
                       CanDelete=rt.CanDelete==null?false:true,
                       MenuId=rt.Menu.Id,
                       MenuName=rt.Menu.MenuName                       
                   });

问题是Employee data未列出

1 个答案:

答案 0 :(得分:2)

我相信这应该是:

from m in _db.Menus
join mr in _db.MenuRoles on m.Id equals mr.MenuID  into t
from rt in t.Where(x=>x.DesignationID==1).DefaultIfEmpty()
where m.ParentID!=0

DesignationID转到left join条件,ParetID转到where条款。

m

中选择
select new MenuVM
{
     CanAdd=rt.CanAdd==null?false:true,
     CanEdit=rt.CanEdit==null?false:true,
     CanDelete=rt.CanDelete==null?false:true,
     MenuId=m.Id,
     MenuName=m.MenuName                       
});