For the table data model involved in this article, refer to the previous article
First, let's look at a simple inner join. when reading the Student table, the inner join Class Table obtains the corresponding Class information:
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();}
This is especially simple, so you don't need to post SQL statements. Continue to look at 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();}
During Outer join, the joined table must be into a new variable gc, and gc. DefaultIfEmpty () is used to represent the Outer join.
Additional notes related to linq to SQL:
1. Starting from CUD, how to insert, modify, and delete data using LINQ to SQL
2. query simple queries using LINQ to SQL
3. query delayed loading and immediate loading, using LoadWith and AssociateWith
4. query inner join and left outer join
5. aggregate grouping having in Linq to SQL
6. Do I have to worry about performance when optimizing the query of LINQ to SQL?