将带有join的SQL查询转换为lambda表达式

时间:2014-04-09 02:21:23

标签: c# sql entity-framework linq-to-entities sql-to-linq-conversion

不确定如何将以下sql转换为lambda表达式。我的数据库使用参照完整性和与Content_Training表相关的表内容,具有1对多的关系(1个内容可以包含许多content_trainings)

select c.ContentId, c.Name, ct.TrainingTypeId 
from dbo.Content c left join dbo.Content_Training ct on c.ContentId = ct.ContentId
where c.PublishDate is not null
order by ct.TrainingTypeId, c.Name

1 个答案:

答案 0 :(得分:2)

尝试此查询:

var results = (from c in dbcontext.Contents
               join ct in dbcontext.Content_Trainings on c.ContentId equals ct.ContentId into t
               from rt in t.DefaultIfEmpty()
               select new
               {
                   c.ContentId,
                   c.Name,
                   TrainingTypeId = (int?)rt.TrainingTypeId
               }).OrderBy(r => r.TrainingTypeId)
                 .ThenBy(r => r.Name);