[LINQ+EF]如何做單一條件JOIN以及複合條件JOIN以及多個table的JOIN

  • 15958
  • 0

摘要:[LINQ+EF]如何做單一條件JOIN以及複合條件JOIN

單一pk的JOIN範例:

//這是join單一pk, 並最後select table2為結果的範例
var table2Object = (from t1 in db.table1
			 join t2 in db.table2 on t1.id equals t2.id			 
			 select t2).FirstOrDefault();

複合pk的JOIN範例:

//這是join多個pk, 並最後select table2為結果的範例
var table2Object = (from t1 in db.table1
			 join t2 in db.table2 
			 on new { t1.id, t1.another_id } equals new { t2.id, t2.another_id }
			 select t2).FirstOrDefault();

補充:join超過兩個的table的寫法:

//這是join三個table, 並最後select table2為結果的範例
var table2Object = (from t1 in db.table1
			 join t2 in db.table2 
			 on new { t1.id, t1.another_id } equals new { t2.id, t2.another_id }
			 join t3 in db.table3
			 on new { t2.id, t2.another_id } equals new { t3.id, t3.another_id }
			 select t2).FirstOrDefault();

參考資料:

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

http://stackoverflow.com/questions/5307731/linq-to-sql-multiple-joins-on-multiple-columns-is-this-possible