2

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);
4
  • Can you please share your LINQ expression? Commented Dec 4, 2012 at 10:14
  • Of course. I've added it now. Commented Dec 4, 2012 at 10:19
  • Check this: [stackoverflow.com/questions/5224339/… [1]: stackoverflow.com/questions/5224339/… Commented Dec 4, 2012 at 10:19
  • Vitality: I'm not sure that'll work. I want to check if ParentMenuCode is null only if ActiveSubMenu is null, if it's not null I want to check if ParentMenuCode is equal to ActiveMenu. Commented Dec 4, 2012 at 10:22

3 Answers 3

4

Why don't you use

mappedColumnName == (myVar == null ? DBNull.Value: myOtherVar)

instead?

Sign up to request clarification or add additional context in comments.

Comments

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)
)

1 Comment

Thank you Jamie! This works, the workaround is also referenced at stackoverflow.com/questions/2097539/…
0

try this

(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);

1 Comment

Same result. The Transact-SQL translation of the ternary expression is a scalar method and Transact-SQL basically tries to perform columnName = null which will always fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.