在LINQ / EF中处理复杂权利外部联接的好策略是什么

时间:2013-02-14 03:37:09

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

我有这个模型

enter image description here

我的目标是为用户检索所有资源,但与该用户共享受限角色的资源除外。

这在直接SQL中并不太难(6BA60C09-2873-46A5-BAFB-5996A6C6482B是用户ID)

SELECT distinct r.Name
FROM  dbo.Resources xr 
INNER JOIN [dbo].[x_Resource_RestrictedRole] rr ON  xr.Id = rr.ResourceId
INNER JOIN [dbo].[aspnet_UsersInRoles] ur ON ur.RoleId = rr.RoleId  
    AND ur.UserId = '6BA60C09-2873-46A5-BAFB-5996A6C6482B'
RIGHT JOIN dbo.Resources r on r.id = xr.id 
WHERE xr.id IS NULL

我无法在EF中找到一个好的策略,因为我无法访问关联表。

可以在LINQ或lambda表达式中完成吗?

1 个答案:

答案 0 :(得分:0)

您有某种疑问,但我会尝试回答您的query

var y = (from xr in context.Resources
         join rr in context.x_Resource_RestrictedRole on xr.Id equals rr.ResourceId
         join ur in context.aspnet_UsersInRoles on rr.RoleId  equals ur.RoleId
         join r in context.Resources on xr.id equals r.id into rJoin
         from r2 in rJoin.DefaultIfEmpty()
         where xr.id == null && ur.UserId = "6BA60C09-2873-46A5-BAFB-5996A6C6482B"
         select new { r.Name }).Distinct(c => c.Name).ToList();