Linq中连接主要有组连接、内连接、左外连接、交叉连接四种。本文主要讲解没连接和左外连接。
本次使用到的数据实体模型具体的创建方法不再累述。该实体模型中包括Student、Course两个表,他们之间是一对多的关系。
内连接与SqL中inner join一样,即找出两个序列的交集
Model1Container model = new Model1Container(); //内连接 var query = from s in model.Student join c in model.Course on s.CourseCno equals c.Cno where c.Cno == 1 select new { ClassID = s.CourseCno, ClassName = c.Cname, Student = new { Name = s.Sname, ID = s.Sno } }; foreach (var item in query) { Response.Write("ClassID:" + item.ClassID + "ClassName:" + item.ClassName + "Name:" + item.Student.Name); }
SELECT [t0].[CourseCno] AS [ClassID], [t1].[Cname] AS [ClassName], [t0].[Sname] AS [Name], [t0].[Sno] AS [ID] FROM [Student] AS [t0] INNER JOIN [Course] AS [t1] ON [t0].[CourseCno] = [t1].[Cno] WHERE [t1].[Cno] = @p0
左外连接与SqL中left join一样
Model1Container model = new Model1Container(); var query = from s in model.Student join c in model.Course on s.CourseCno equals c.Cno into gc from gci in gc.DefaultIfEmpty() select new { ClassID = s.CourseCno, ClassName = gci.Cname, Student = new { Name = s.Sname, ID = s.Sno } }; //Outer join时必须将join后的表into到一个新的变量gc中,然后要用gc.DefaultIfEmpty()表示外连接。 foreach (var item in query) { Response.Write("ClassID:" + item.ClassID + "ClassName:" + item.ClassName + "Name:" + item.Student.Name); }
注:上例中使用了DefaultIfEmpty操作符,它能够为实序列提供一个默认的元素。DefaultIfEmpty使用了泛型中的default关键字。default关键字对于引用类型将返回null,而对于值类型则返回0。对于结构体类型,则会根据其成员类型将它们相应地初始化为null(引用类型)或0(值类型)
我们可以不使用default关键字,但在要DefaultIfEmpty中给定当空时的默认对象值。语句如下:
//left join, 为空时使用默认对象 var leftJoinQuery = from s in model.Student join c in model.Course on s.CourseCno equals c.Cno into gc from gci in gc.DefaultIfEmpty( new Course { Cname = "",Cperiod="" } //设置为空时的默认值 ) select new { ClassID = s.CourseCno, ClassName = gci.Cname, };与上面的左外连接语句相对应的SQL脚本语言如下所示:
SELECT [t0].[CourseCno] AS [ClassID], [t1].[Cname] AS [ClassName], [t0].[Sname] AS [Name], [t0].[Sno] AS [ID] FROM [Student] AS [t0] LEFT OUTER JOIN [Course] AS [t1] ON [t0].[CourseCno] = [t1].[Cno]当然也可以通过LinqPad工具查看上面的左外连接语句的Lamada表达式,在此不再累述。
以上是自己学习时的一点见解,不对之处请拍砖指教。