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插入、修改、删除数据

2.  查询 使用LINQ to SQL做简单查询

3.  查询 延迟加载与立即加载,使用LoadWith和AssociateWith

4.  查询 inner join,left outer join

5.  Linq to SQL中的聚合grouping having

6.  LINQ to SQL查询优化,需要忧虑性能吗?

posted @ 2010-05-17 15:45  玉开  阅读(23127)  评论(4编辑  收藏  举报