2011-06-12 229 views
3

如何在LINQ to Entities中編寫以下SQL?左外連接Linq to Entities/SQL

SELECT r.rolename, 
     (CASE 
      WHEN ur.username IS NULL THEN 0 
      ELSE 1 
     END) AS isinrole 
FROM bgt.roles r 
     LEFT OUTER JOIN bgt.usersinroles ur 
     ON ur.rolename = r.rolename 
      AND ur.username = 'ADMIN' 
+0

變種查詢=從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

+0

我聽說EF中不支持DefaultIfEmpty。這是真的嗎? – Harindaka 2011-06-12 12:36:10

+0

自EF 4.0開始支持DefaultIfEmpty' – 2011-06-12 13:28:37

回答

3

這對我有用。感謝所有的建議。

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]) 
2

我會做這樣的:

from role in db.Roles 
let isInRole = role.UsersInRoles.Any(u => u.UserName == "ADMIN") 
select new { role.RoleName, isInRole } 

Althought生成的SQL是不是一樣好你的。

+0

謝謝你讓我朝正確的方向發展。以下爲解決方案。 – Harindaka 2011-06-14 14:23:54