有兩個表格,學校和學期。學校記錄必須顯示,但記錄的詞語可能尚不存在,因此,該詞可能爲空(即左連接)。如果存在,則必須按照當前術語的日期過濾左連接表。這可以在LINQ中完成嗎?將此SQL與左連接轉換爲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
UPDATE:
一些輸入後,我有一個左連接,但如果一所學校缺少一個學期,我仍然不能使開始和結束日期顯示爲空 - 學校不顯示在所有如果我錯過了一個學期,我想讓學校在第一欄中展示。我在想什麼?這是最新的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同樣的事情:
https://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9#leftouterjoin –