将此SQL与左连接转换为LINQ

时间:2017-10-21 22:25:16

标签: sql linq sql-to-linq-conversion

有两个表,学校和学期。必须显示学校记录,但术语记录可能尚不存在,因此,该术语可能为空(因此左连接)。必须按当前术语的日期过滤左连接表(如果存在)。可以在LINQ中完成吗?

select school.school_name, term.term_start, term.term_end 
from school
left join term on school.school_id = term.school_id and term.term_start <= '2017-10-21' and term.term_end >= '2017-10-21'
where school.active = 1 
order by school.school_name

更新:

经过一些输入我有一个左连接但如果学校缺少一个学期,我仍然无法使开始和结束日期显示为空 - 如果我错过了一个学期,学校根本不会显示,并且我希望学校在第一栏中展示。我错过了什么?这是最新的LinqPad代码。

var query =  ((from sc in Schools.Where(s => s.Active == 1 )
             join t in Terms on sc.School_id equals t.School_id into ts
             from tsub in ts.DefaultIfEmpty()
             select new {name = sc.School_name, 
                         start = tsub.Term_start,
                         end = tsub.Term_end})
             .Where (o => o.start <= DateTime.Now && o.end >= DateTime.Now))
             .OrderBy( o => o.name);

query.Dump();

更新#2

以下是SQL结果的屏幕截图,我试图在LINQ中实现相同的功能:

enter image description here

2 个答案:

答案 0 :(得分:0)

var query =  from sc in school.Where(s = > s.active == 1 )
             join t in term on sc.school_id == t.school_id
             select new {name = sc.school_name, 
                         start = t.term_start,
                         end =  term.term_end}
             .Where (o => o.start <= '2017-10-21' && o.end >= '2017-10-21')
             .OrderBy( o => o.school_name) 

答案 1 :(得分:-1)

我终于明白了。如果将.Where()子句放在连接表上,则在没有匹配记录时将获得空值。这是LinqPad LINQ语句,它可以在.NET MVC中完美运行。

var query =  ((from sc in Schools.Where(s => s.Active == 1 )
             join t in Terms.Where(x => x.Term_start <= DateTime.Now && x.Term_end >= DateTime.Now) on sc.School_id equals t.School_id into ts
             from tsub in ts.DefaultIfEmpty()
             select new {name = sc.School_name, 
                         start = tsub.Term_start,
                         end = tsub.Term_end})
             .OrderBy( o => o.name));

query.Dump();