• Linq to SQL 的连表查询(转)


    关于数据库的查询中经常需要用到多表的连接查询,这里就简单地展示关于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()方法。
  • 相关阅读:
    jvm内存模型
    tomcat下出现The file is absent or does not have execute&
    linux下安装apache
    什么时候能踏上征程?追寻真正的自由和信仰
    linux基础命令
    UVALive 7263 Today Is a Rainy Day
    HDU 6071 Lazy Running
    HihoCoder 1634 Puzzle Game
    HDU 6228 Tree
    HDU 2222 Keywords Search AC自动机模版
  • 原文地址:https://www.cnblogs.com/zhengqian/p/7807866.html
Copyright © 2020-2023  润新知