【发布时间】:2013-12-09 03:04:24
【问题描述】:
工作:
我正在尝试在我的 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值allowed的行。
尝试:
我以为我可以这样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 值记录?
【问题讨论】:
-
您是通过运行实际检查查询结果还是只是尝试查看已翻译的 SQL 查询?看起来
allowed总是被翻译成false。 -
我在 LinqPad 中运行了查询,它显示了 SQL 输出。它没有返回预期的结果集。
-
我没有太多使用 LINQPad,只是使用了它的一些功能,但我认为您应该在 Visual Studio 中尝试您的代码。
标签: c# mysql linq lightspeed