例子:
var query =
from r in db.Roles
join sr in
(
from ss in db.StaffInRoles
where ss.StaffId == staffId
select ss
)
on r.Id equals sr.RoleId
into x
from y in x.DefaultIfEmpty()
select new RoleInfo
{
RoleId = r.Id,
RoleName = r.Name,
IsSet = y != null
};
from r in db.Roles
join sr in
(
from ss in db.StaffInRoles
where ss.StaffId == staffId
select ss
)
on r.Id equals sr.RoleId
into x
from y in x.DefaultIfEmpty()
select new RoleInfo
{
RoleId = r.Id,
RoleName = r.Name,
IsSet = y != null
};
注意这里最后可以通过 y != null 来判断右值是否为空。
这个 Linq to sql 语句生成的对应 SQL 为:
exec sp_executesql N'SELECT [t0].[Id] AS [RoleId], [t0].[Name] AS [RoleName],
(CASE
WHEN [t2].[test] IS NOT NULL THEN 1
ELSE 0
END) AS [IsSet]
FROM [Role] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[StaffId], [t1].[RoleId]
FROM [StaffInRole] AS [t1]
) AS [t2] ON ([t0].[Id] = [t2].[RoleId]) AND ([t2].[StaffId] = @p0)',N'@p0 int',@p0=1
(CASE
WHEN [t2].[test] IS NOT NULL THEN 1
ELSE 0
END) AS [IsSet]
FROM [Role] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[StaffId], [t1].[RoleId]
FROM [StaffInRole] AS [t1]
) AS [t2] ON ([t0].[Id] = [t2].[RoleId]) AND ([t2].[StaffId] = @p0)',N'@p0 int',@p0=1
over.