我正在使用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
};
谢谢
答案 0 :(得分: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
});