Linq学习(五)-多表连接

本将主要介绍 内连接与 外连接

1.join

Linq to sql

from a in Blog_Users
join b in Blog_UserInfo
on  a.UserId equals b.ID
select new
{
    昵称=a.NickName,
    真实名=b.RealName
}

sql

SELECT [t0].[NickName] AS [昵称], [t1].[RealName] AS [真实名]
FROM [Blog_User] AS [t0]
INNER JOIN [Blog_UserInfo] AS [t1] ON ([t0].[UserId]) = [t1].[ID]

Lambda

Blog_Users
   .Join (
      Blog_UserInfo, 
      a => (Int32?)(a.UserId), 
      b => b.ID, 
      (a, b) => 
         new  
         {
            昵称 = a.NickName, 
            真实名 = b.RealName
         }
   )

2.外连接

Linq to sql

from a in Blog_Users
join b in Blog_UserInfo
on  a.UserId equals b.ID
into ab
from c in ab.DefaultIfEmpty()
select new
{
    昵称=a.NickName,
    真实名=c.RealName
}

sql

SELECT [t0].[NickName] AS [昵称], [t1].[RealName] AS [真实名]
FROM [Blog_User] AS [t0]
LEFT OUTER JOIN [Blog_UserInfo] AS [t1] ON ([t0].[UserId]) = [t1].[ID]

Lambda

Blog_Users
   .GroupJoin (
      Blog_UserInfo, 
      a => (Int32?)(a.UserId), 
      b => b.ID, 
      (a, ab) => 
         new  
         {
            a = a, 
            ab = ab
         }
   )
   .SelectMany (
      temp0 => temp0.ab.DefaultIfEmpty (), 
      (temp0, c) => 
         new  
         {
            昵称 = temp0.a.NickName, 
            真实名 = c.RealName
         }
   )
posted @ 2016-01-30 23:20  Kimisme  阅读(754)  评论(0编辑  收藏  举报