1

我正在使用 Sql Server 2012 和 .NET 4

我想转换为 C# 的 Sql 如下所示:

SELECT rd.Name, rd.Description, prdv.Value
FROM RoleDetail rd 
    JOIN Role r ON r.RoleID = rd.RoleID
    JOIN PersonRole pr ON pr.RoleID = r.RoleID
    LEFT OUTER JOIN PersonRoleDetailValue prdv ON prdv.RoleDetailID = rd.RoleDetailID
WHERE pr.PersonID = 42

在几次尝试和浪费了很多时间之后,我似乎并没有比开始时更好。任何帮助表示赞赏。

我更喜欢方法语法,但查询语法解决方案也非常受欢迎。

解决方案(感谢下面大卫 B 的回答)

以下是两个有效的解决方案。我希望其他人可以受益...

方法语法:

var methodSyntax = db.PersonRoles
    .Where(pr => pr.PersonID == 42)
    .SelectMany(pr => pr.Role.RoleDetails)
    .SelectMany(rd => rd.PersonRoleDetailValues.DefaultIfEmpty(), (rd, prdv) => new
        {
            Name = rd.Name,
            Description = rd.Description,
            Value = prdv.Value
        });

查询语法:

var querySyntax = from pr in db.PersonRoles
     where pr.PersonID == 42
     let r = pr.Role
     from rd in r.RoleDetails
     from prdv in rd.PersonRoleDetailValues.DefaultIfEmpty()
     select new
     {
         Name = rd.Name,
         Description = rd.Description,
         Value = prdv.Value
     };

谢谢

4

1 回答 1

2

如果您的映射设置正确,则您的类型之间应该有导航属性。这使您可以开始查询一种类型并包括其他类型,而无需一遍又一遍地指定连接的列。

from pr in dataContext.PersonRoles
where pr.PersonId = 42
  //navigation property Many->One  Queryable.Select
let r = pr.Role  
  //navigation property One->Many  Queryable.SelectMany
from rd in r.RoleDetails
  //navigation property One->Many, match null if none
from prdv = rd.PersonRoleDetailValues.DefaultIfEmpty()
select new
{
  Name = rd.Name,
  Description = rd.Description,
  Value = prdv.Value
}

为了好玩,方法语法尽可能简洁:

dataContext.PersonRoles
  .Where(pr => pr.PersonId = 42)
  .SelectMany(pr => pr.Role.RoleDetails)
  .SelectMany(rd => rd.PersonRoleDetailValues.DefaultIfEmpty(),
    (rd, prdv) => new
  {
    Name = rd.Name,
    Description = rd.Description,
    Value = prdv.Value
  });
于 2013-07-24T01:56:16.483 回答