c# - 在 LINQ WHERE 子句中有条件地允许 null

标签 c# mysql linq lightspeed

工作:

我正在尝试在我的 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/

相关文章:

php - 按计算距离对 MySQL 结果进行排序(距离未存储在 DB 中)

c# - 查询 TreeNodeCollection

c# - ForEach循环不改变类的属性

c# - 我如何控制我的图像并在我的 ListView 中使用它创建动画?

c# - EF 代理和复杂的数据结构

c# - 如何将参数传递给 C# 中的直通查询?

mysql - 将字符串转换为 INT mysql

Python raw_input 故障并返回 -bash : line 1: <INPUT>: command not found

c# - Linq - 如何在 Linq 中获取查询结果并将其添加到数组中

c# - 使用 LINQ,如何根据部分字符串属性过滤集合?