带LEFT JOIN的LINQ请求返回不是预期的结果

时间:2012-02-14 11:54:16

标签: .net entity-framework linq-to-entities

请帮我将此查询转换为Linq to Entities。

SELECT 
    d.`DepartmentId`,
    d.`ParentDepartmentId`,
    d.`LeftKey`,
    d.`RightKey`,
    udp.`UserId`,
    udp.`IsAllowed` 
FROM
    Departments AS d 
    LEFT JOIN UserDepartmentPermissions AS udp 
        ON udp.`DepartmentId` = d.`DepartmentId`
WHERE d.`IsExcluded` = 0

我想这个:

(from d in Departments
   join udp in UserDepartmentPermissions 
   on d.DepartmentId equals udp.DepartmentId into JoindedDepsUserPermissions
   from udp in JoindedDepsUserPermissions.DefaultIfEmpty()
   where d.IsExcluded == 0
   select  new
     {
      d.DepartmentId,
      d.ParentDepartmentId,
      d.LeftKey,
      d.RightKey,
      udp.UserId,
      udp.IsAllowed
     }).ToList();

但它没有返回相同的结果......

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

尝试

var result = Deparments.Where(d => d.IsExcluded == 0)
             .Select(d => new {
                   d.DepartmentId,
                   d.ParentDepartmentId,
                   d.LeftKey,
                   d.RightKey,
                   d.Permissions
                 });

使用Department中的导航属性访问权限