工作:
我正在尝试在我的 Contacts
表和我的 Permissions
表之间执行 LEFT OUTER JOIN。我有这个正常工作的基础,无论他们是否有相应的权限,都会得到一个联系人列表。
// Query for Contacts
from contact in Contacts
join permission in Permissions on contact.Id equals permission.ObjectId into permissionGrp
from p in permissionGrp.DefaultIfEmpty()
where p==null || (p!=null && /* ... condition based on the existence of a permission */)
select new { contact, permission = p };
生成的 WHERE SQL:
WHERE
(t1.PermissionId IS NULL OR
((t1.PermissionId IS NOT NULL AND ... other conditions ... )))
问题:
我想修改以上内容以引入“后备”检查;未按预期工作。
要求:
- 当没有
Contact
对应的Permission
时(即p==null
)则只包含基于预定bool
允许
的值。
尝试:
我想我可以做 where (p==null && allowed) || ...
像这样:
// Fallback permission
bool allowed = false;
// Query for Contacts
from contact in Contacts
join permission in Permissions on contact.Id equals permission.ObjectId into permissionGrp
from p in permissionGrp.DefaultIfEmpty()
/* Added bool condition 'allowed' to control inclusion when 'p' is null */
where (p==null && allowed) || (p!=null && /* ... condition based on the existence of a permission */)
select new { contact, permission = p };
预期:
当allowed = false
时(不接受null
权限)
WHERE
((t1.PermissionId IS NOT NULL AND ... other conditions ... ))
当allowed = true
时(接受null
权限)
WHERE
(t1.PermissionId IS NULL OR
((t1.PermissionId IS NOT NULL AND ... other conditions ... )))
实际结果:
即使在 true
时也始终输出为 allowed=false
?
WHERE
((t1.PermissionId IS NOT NULL AND ... other conditions ... ))
总结:
我希望我只是在做一些很容易修复的傻事。
如何根据给定的 bool
值过滤我的 null
值记录?
最佳答案
您正在执行 GroupJoin
这里。所以第一部分的结果,permissionGrp
, 是匿名类型 IGrouping<Permission>
.这已经是 OUTER JOIN 的等价物。
您可以通过有条件地测试 IGrouping<Permission>
是否满足您的要求。包含元素:
from contact in Contacts
join permission in Permissions on contact.Id equals permission.ObjectId
into permissionGrp
where allowed || g.Any()
from p in permissionGrp.DefaultIfEmpty()
select new { contact, permission = p };
请注意 from p in permissionGrp
再次展平分组,所以 .DefaultIfEmpty()
对于 allowed == true
的情况仍然是必要的.
关于c# - 在 LINQ WHERE 子句中有条件地允许 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20175266/