将复杂的T-SQL查询转换为LINQ to Entities

时间:2016-01-21 18:52:41

标签: c# sql linq

这是产生正确结果的SQL代码:

select s.Code, s.Name, coalesce(ss.Url,  a.Url), a.SocialMediaTypeKey
from School s
Left join 
(
SELECT dbo.SchoolSocialMedia.SocialMediaTypeKey
, SchoolSocialMedia.Url
, dbo.Department.Name
, dbo.Department.ImportBusinessKey
FROM dbo.SchoolSocialMedia 
    INNER JOIN dbo.Department ON dbo.SchoolSocialMedia.DepartmentId =   dbo.Department.Id
) A 
ON 1 = 1
Left join dbo.SchoolSocialMedia ss ON ss.SchoolId = s.Id and    ss.SocialMediaTypeKey = a.SocialMediaTypeKey
where  s.[DeactivatedDate] is null

这是我在C#中取得的成就,但它没有产生正确的结果 - 事实上,它返回零结果:

        var departmentSocialMediaResult =
            from ssm in context.SchoolSocialMedia
            from d in context.Department.Where(d => d.Id == ssm.DepartmentId)
            select new { ssm.SocialMediaTypeKey,
                ssm.Url,
                d.Name,
                ssm.SchoolId };
        var result =
            (from s in context.School
             from ssm in context.SchoolSocialMedia.DefaultIfEmpty()
             from dssm in departmentSocialMediaResult.DefaultIfEmpty()
             .Where(dssm => dssm.SchoolId == s.Id && dssm.SocialMediaTypeKey == ssm.SocialMediaTypeKey)
             select new { ssm.SchoolId, ssm.SocialMediaTypeKey, ssm.Url })
             .ToDictionary(ssm => new SchoolSocialMediaKey(
                    ssm.SchoolId, ssm.SocialMediaTypeKey),
                ssm => ssm.Url);

有没有人对如何更好地将T-SQL转换为LINQ到实体有任何建议?我究竟做错了什么? TIA。

更新

谢谢@Aducci,您的回答是正确答案。由于结果被放入字典中,这就是我最终使用的内容:

        var query =
            (from s in context.School
            from a in
            (
               from ssm in context.SchoolSocialMedia
               join d in context.Department on ssm.DepartmentId equals d.Id
               select new
               {
                   ssm.SocialMediaTypeKey,
                   ssm.Url,
                   d.Name
               }
            ).DefaultIfEmpty()
            from ss in context.SchoolSocialMedia
                              .Where(x => s.Id == x.SchoolId)
                              .Where(x => a.SocialMediaTypeKey == x.SocialMediaTypeKey)
                              .DefaultIfEmpty()
            select new
            {
                ss.SchoolId,
                Url = ss.Url ?? a.Url,
                a.SocialMediaTypeKey
            }).Distinct();

        return
            query
            .ToDictionary(
                ssm => new SchoolSocialMediaKey(
                    ssm.SchoolId, ssm.SocialMediaTypeKey),
                ssm => ssm.Url);

1 个答案:

答案 0 :(得分:1)

我确信有更好的方法来编写原始查询,但不是花太多时间分析我只是将其翻译成linq。通常,您的linq查询应该具有与tsql查询相同的结构,如下所示:

<td />