码迷,mamicode.com
首页 > 数据库 > 详细

LINQ to SQL系列四 使用inner join,outer join

时间:2015-08-14 15:04:48      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

先看一个最简单的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查询优化,需要忧虑性能吗?

LINQ to SQL系列四 使用inner join,outer join

标签:

原文地址:http://www.cnblogs.com/superfeeling/p/4729805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!