這對我有用。感謝所有的建議。
var query =
from r in Roles
from ur in UsersInRoles
.Where(v => v.Rolename == r.Rolename && v.Username == "ADMIN")
.DefaultIfEmpty()
select new { Rolename = r.Rolename, IsInRole = (ur.Username != null) };
生成的SQL是如在角色如下
SELECT
1 AS [C1],
[Extent1].[Rolename] AS [Rolename],
CASE WHEN ([Extent2].[Username] IS NOT NULL) THEN cast(1 as bit) WHEN ([Extent2].[Username] IS NULL) THEN cast(0 as bit) END AS [C2]
FROM [bgt].[Roles] AS [Extent1]
LEFT OUTER JOIN [bgt].[UsersInRoles] AS [Extent2] ON ([Extent2].[Rolename] = [Extent1].[Rolename]) AND ('ADMIN' = [Extent2].[Username])
變種查詢=從r 加入烏爾在UsersInRoles上新{F1 = r.Rolename,F2 = 'ADMIN'} 等於新的{ f1 = ur.Rolename,f2 = ur.Username}從temp.DefaultIfEmpty()中輸入temp () select new {f1 = r.RoleName,f2 = x.Username}; – Harindaka 2011-06-12 12:35:18
我聽說EF中不支持DefaultIfEmpty。這是真的嗎? – Harindaka 2011-06-12 12:36:10
自EF 4.0開始支持DefaultIfEmpty' – 2011-06-12 13:28:37