Linq To Sql 中使用lambda表达式实现Left Join
网上也有很多有关Linq To Sql实现Left join的例子,不过使用lambda的不多,就算使用lambda的,也讲得很含糊,本来不需要讲太多废话的,硬要讲得高深莫测,显得好厉害。那些高深的东西在这里我也不讲了,也不会讲,直接上代码就知道了:
当前有两个表,TUsers与TUserInfo,两者通过UserID关联,而TUsers表记录的是必须的数据,而TUserInfo记录是一些附件的数据,因此在TUserInfo中不一定有数据。使用Left Join获取数据:
Lambda表达式如下:
TUsers.GroupJoin(
TUserInfo,
u => u.UserID,
ui => ui.UserID,
(u, ui) => new { u, ui }).Select(o => o)
在LinqPad中查看结果,正常显示,查看生成的SQL语句如下:
SELECT [t0].[UserID], [t0].[UserName], [t0].[RealName], [t0].[NickName], [t0].[Password], [t0].[RegTime], [t0].[LastLoginTime], [t0].[IsLocked], [t0].[RoleID], [t1].[UserID] AS [UserID2], [t1].[City], [t1].[Address], [t1].[Telephone], [t1].[Mobile], [t1].[ZipCode], [t1].[Gender], [t1].[Birthday], [t1].[QQ], [t1].[MSN], [t1].[Email], [t1].[HomePage], [t1].[Photo], [t1].[HeadPic], [t1].[PWQ], [t1].[PWA], [t1].[Motto], (
SELECT COUNT(*)
FROM [TUserInfo] AS [t2]
WHERE [t0].[UserID] = [t2].[UserID]
) AS [value]
FROM [TUser] AS [t0]
LEFT OUTER JOIN [TUserInfo] AS [t1] ON [t0].[UserID] = [t1].[UserID]
ORDER BY [t0].[UserID]
SELECT COUNT(*)
FROM [TUserInfo] AS [t2]
WHERE [t0].[UserID] = [t2].[UserID]
) AS [value]
FROM [TUser] AS [t0]
LEFT OUTER JOIN [TUserInfo] AS [t1] ON [t0].[UserID] = [t1].[UserID]
ORDER BY [t0].[UserID]
在代码中测试也可通过;