LINQ to SQL系列四 使用inner join,outer join
本文中涉及的表数据模型请参考上一篇文章
先看一个最简单的inner join,在读取Student表时inner join Class表取的对应的Class信息:
static void Main(string[] args) { using (var writer = new StreamWriter(WatchSqlPath, false, Encoding.UTF8)) { using (DbAppDataContext db = new DbAppDataContext()) { db.Log = writer; //inner join var query = from s in db.Students join c in db.Classes on s.ClassID equals c.ClassID where c.ClassID == 1 select new { ClassID = s.ClassID, ClassName = c.ClassName, Student = new { Name = s.Name, ID = s.StudentID } }; foreach (var item in query) { Console.WriteLine("{0} {1} {2}", item.ClassID, item.ClassName, item.Student.Name); } } } Console.ReadLine(); }
特别简单,就不贴sql了,继续看outer join:
static void Main(string[] args) { using (var writer = new StreamWriter(WatchSqlPath, false, Encoding.UTF8)) { using (DbAppDataContext db = new DbAppDataContext()) { db.Log = writer; //left outer join var query = from s in db.Students join c in db.Classes on s.ClassID equals c.ClassID into gc from gci in gc.DefaultIfEmpty() select new { ClassID = s.ClassID, ClassName = gci.ClassName, Student = new { Name = s.Name, ID = s.StudentID } }; foreach (var item in query) { Console.WriteLine("{0} {1} {2}", item.ClassID, item.ClassName, item.Student.Name); } } } Console.ReadLine(); }
Outer join时必须将join后的表into到一个新的变量gc中,然后要用gc.DefaultIfEmpty()表示外连接。
linq to sql相关随笔:
1. 从CUD开始,如何使用LINQ to SQL插入、修改、删除数据
3. 查询 延迟加载与立即加载,使用LoadWith和AssociateWith
4. 查询 inner join,left outer join