左外连接到Linq到Entities / SQL

时间:2011-06-12 12:30:47

标签: sql linq entity-framework linq-to-entities

如何在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'  

2 个答案:

答案 0 :(得分: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])

答案 1 :(得分:2)

我会这样做:

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

虽然生成的SQL不如你的好。