Trying to read a dataContext class like this
var users = new List<User>();
var roles = new int[] { 1, 2 };
// here I need to get users who's role is in role (1, 2), hence above line
// and also I need to get user who's isValid field true, please note that isValid is SQL 'bit' field and is nullable
//This is what I am doing
foreach (var user in dataContext.Users
.Where(u => roles.Contains(u.RoleID.Value)
&& u.isValid ?? false == true)) // here '&&' part I'm struggling and getting above error
{
users.Add(new User()
{
// Users Added in collection
});
}
So the question is in where clause I need to get user's who are in role(1,2) && isValid == true, if isValid is 'null' make it false. Thanks
In programming, an operator is a symbol that operates on a value or a variable. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.
An operator is a person who is employed to operate or control a machine. ... computer operators. An operator is a person or a company that runs a business.
Definition: A Business Operator is the primary force driving a team working towards fulfillment of a company vision. This may be a dedicated team of contractors, but usually includes a mixture of contractors and employees.
You have to wrap it in parentheses:
roles.Contains(u.RoleID.Value) && (u.isValid ?? false)
bit of confused with (u.isValid ?? false), does this not mean that if u.isValid == null then make it false and look for users where u.isValid is false, this is not what I want.
No, it just means that nulls
are treated as false
and that all users are taken which isValid
is neither null
nor false
. It works because the ??
-operator converts the Nullable<bool>
to a bool
, so you can use it with &&
. I don't like it, i prefer explicit code that i understand later:
roles.Contains(u.RoleID.Value) && u.isValid.HasValue && u.isValid.Value
or simpler by using the ==
-operator with the bool?
:
roles.Contains(u.RoleID.Value) && u.isValid == true
Given bool
will default to false
anyway you could use GetValueOrDefault
roles.Contains(u.RoleID.Value) && u.isValid.GetValueOrDefault()
Note - GetValueOrDefault
does not appear to be supported by EF - see ticket
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With