从Sql到Linq再到Sql

本文关键字:Sql 再到 Linq | 更新日期: 2023-09-27 18:24:29

我使用的是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

经过几次尝试和浪费了很多时间,我似乎并没有比刚开始的时候更好。感谢您的帮助。

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

解决方案(感谢David 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
     };

感谢

从Sql到Linq再到Sql

如果映射设置正确,那么类型之间应该有导航属性。这使您可以启动关于一种类型的查询并包括其他类型,而无需反复指定联接的列。

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