Working:
I am trying to perform a LEFT OUTER JOIN between my Contacts
table and my Permissions
table. I have the basis of this working correctly, and get back a list of contacts regardless of whether they have a corresponding permission.
// 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 };
Generated WHERE SQL:
WHERE
(t1.PermissionId IS NULL OR
((t1.PermissionId IS NOT NULL AND ... other conditions ... )))
Problem:
I want to adapt the above to introduce 'fallback' check; Not working as expected.
Requirement:
- When there is no
Permission
corresponding to theContact
(i.e.p==null
) then only include the row based on the predeterminedbool
value ofallowed
.
Attempt:
I thought I could do where (p==null && allowed) || ...
like this:
// 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 };
Expected:
When allowed = false
(don't accept null
permission)
WHERE
((t1.PermissionId IS NOT NULL AND ... other conditions ... ))
When allowed = true
(accept null
permission)
WHERE
(t1.PermissionId IS NULL OR
((t1.PermissionId IS NOT NULL AND ... other conditions ... )))
Actual Result:
Always outputs as if allowed=false
even when true
?
WHERE
((t1.PermissionId IS NOT NULL AND ... other conditions ... ))
Summary:
I hope I am just doing something silly that's easily fixed.
How can I filter my null
value records based on a given bool
value?