LINQ 中的 C# 左连接

Van*_*ith 0 c# sql linq entity-framework

不确定如何将以下 sql 转换为 LINQ 表达式。我的数据库确实使用参照完整性,并且表内容与表 Content_Training 以 1 对多的关系(例如:1 个内容可以有多个 content_trainings)。

select c.ContentId, c.Name, ct.TrainingTypeId 
from dbo.Content c left join dbo.ContentTraining ct on c.ContentId = ct.ContentId
where c.ExpirationDate is not null
order by ct.TrainingTypeId, c.Name
Run Code Online (Sandbox Code Playgroud)

我试过这个,这似乎有效。但是,我不确定“let”关键字的用法。

var data = (from c in context.Contents
let ct = ( from t in context.Content_Training where t.ContentId == c.ContentId
select new { t.TrainingTypeId } ).FirstOrDefault()
where c.ExpirationDate.HasValue
orderby ct.TrainingTypeId, c.Name
select new { c.ContentId, c.Name, ct.TrainingTypeId } ).ToList();
Run Code Online (Sandbox Code Playgroud)

Ras*_*dit 7

对于左连接,您需要使用 DefaultIfEmpty()

您的查询应该类似于:

var query = from c in Content
            join ct in ContentTraining
            on c.ContentId equals ct.ContentId into g
            from ct in g.DefaultIfEmpty()
            where c.ExpirationDate != null
            select new
            {     
                c.ContentId, 
                c.Name, 
                ct.TrainingTypeId 
             }).ToList();
Run Code Online (Sandbox Code Playgroud)

请参考linq 中的左外连接

http://msdn.microsoft.com/en-us/library/bb397895.aspx