Zoe
关于数据库的查询中经常需要用到多表的连接查询,这里就简单地展示关于linq的查询功能。

1、单表的查询

[csharp] view plain copy

    var query = from tc in db.tbClass  
             where tc.ClassID == "1"  
                //查询表tbClass  
            select new {  
            ClassID=tc.ClassID,  
            ClassName=tc.ClassName  
                }  

2、多表内连接查询

[csharp] view plain copy

    var query = from s in db.tbStudents  
                                join c in db.tbClass on s.ClassID equals c.ClassID  
                                where s.ClassID == 3  
                                select new  
                                {  
                                    ClassID = s.ClassID,  
                                    ClassName = c.ClassName,  
                                    Student = new  
                                    {  
                                        Name = s.Name,  
                                        StudentID = s.StudentID  
                                    }  
                                };  

内连接与SqL中inner join一样,即找出两个序列的交集。

3、外连接

[csharp] view plain copy

    var query = from s in db.tbStudents  
                                join c in db.tbClass on s.ClassID equals c.ClassID into tbC  
                                from tbCw in tbC.DefaultIfEmpty()  
                                where s.ClassID == 3  
                                select new  
                                {  
                                    ClassID = s.ClassID,  
                                    ClassName = tbCw.ClassName,  
                                    Student = new  
                                    {  
                                        Name = s.Name,  
                                        StudentID = s.StudentID  
                                    }  
                                };  

注意点在与外连接的时候 from外接表的时候需要进行into到新的变量中,然后进行调用DefaultIfEmpty()方法。

 

posted on 2017-11-09 09:36  口袋里的SKY  阅读(430)  评论(0编辑  收藏  举报