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

3

不确定如何将以下SQL转换为Lambda表达式。我的数据库使用引用完整性,并且在一个Content_Training表中,Content表与之关联是一对多的关系(1个Content可以有多个Content_Training)

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个回答

3

试试这个查询:

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

我经常使用查询语法,而不是lambda表达式,例如 orderby x,y。这样更容易阅读。 - abatishchev
谢谢Abatishchev。过去我使用的是“let”关键字而不是你使用的“into t ... t.DefaultIfEmpty()”。这两者有什么区别? - BeYourOwnGod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接