Using ternary operator to check if null - null reference is not the same as null
24,085
Solution 1
I've never actually attempted to use ternary operators in linq although you could write it as:
(
(myVar == null && mappedColumnName == null ) ||
(myVar != null && mappedColumnNmae == myOtherVar)
)
Solution 2
Why don't you use
mappedColumnName == (myVar == null ? DBNull.Value: myOtherVar)
instead?
Comments
-
Maritim almost 2 years
I am attempting to use the ternary operator to check if a value is null and return one expression or the other. What I'm experiencing when incorporating this into a LINQ expression is that the Transact-SQL translation of the LINQ expression attempts to do a "column = null" rather than a "column IS NULL". I have reason to believe that this is because I'm doing the following:
mappedColumnName == (myVar == null ? null : myOtherVar)
Since it translates the following to columnName IS NULL in Transact-SQL:
mappedColumnName == null
Does anyone have any experience with this? I'd very much like to get this to work.
The entire LINQ expression:
(from MenuItem in menuContext.Menus where MenuItem.IsSysAdmin == (ClientID == 1 ? true : false) && MenuItem.IsActive == true && MenuItem.ParentMenuCode == (ActiveSubMenu==null?null:ActiveMenu) && MenuItem.ClientID == (UseClientMenu ? ClientID : 0) && MenuItem.EmployeeID == (UseEmployeeMenu ? EmployeeID : 0) orderby MenuItem.SortOrder, MenuItem.MenuName select MenuItem);