I got this question from a mentee the other day. They were trying to do the following:
foreach (var user in dbContext.Users.Where(
u => roles.Contains(targetRole) &&
u.Valid ?? false == true))
{
<code...>
}
Unfortunately, they kept getting the compiler error above. The Valid field in the database is configured as a bit value that is nullable and they want it to return false if it's null.
The fix is straight forward by simply using parentheses thus:
foreach (var user in dbContext.Users.Where(
u => roles.Contains(targetRole) &&
(
u.Valid ?? false)))
{
<code...>
}
The double question mark (??) tells C# to return the following value if the preceding is null. If it isn't null, it will simply process the value as either true or false.
Later
C
C
No comments:
Post a Comment
Comments are moderated only for the purpose of keeping pesky spammers at bay.