1

I have a query that returns null reference exception. I'm filter data using searching, I put breakpoint and check that the problem is that when a column has a null value it returns exception.

Controller:

if (searchValue != null || searchValue != "")
{
     expheadlist = expheadlist.Where(e => 
                    e.Name.ToLower().Contains(searchValue) || 
                    e.Description.ToLower().Contains(searchValue) 
                    ).ToList<GenExpenseHead>();
}

I allowed null values in Description attribute. This entity has a null value in Description column. I think therefore it returns NullException in this code. I don't know how to resolve it.

Thanks in Advance.

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
Huzaifa
  • 83
  • 1
  • 12
  • Use ...`e.Description?.ToLower`... the db can handle nulls, but c# can't call method on null reference. But it looks, that this is executed as linq to objects and not ef linq, should see how the source of this qury us prepared. – ZorgoZ Dec 26 '18 at 07:56

3 Answers3

5

You cannot write ?. (null conditional operator) and ?? (null coalescing operator) in Where clause. Instead use string.IsNullOrWhiteSpace in your query as follows:

if (!String.IsNullOrWhiteSpace(searchValue))
{
     expheadlist = expheadlist.Where(e => (string.IsNullOrWhiteSpace(e.Name) || e.Name.ToLower().Contains(searchValue))
                    || (string.IsNullOrWhiteSpace(e.Description) || e.Description.ToLower().Contains(searchValue))
                    ).ToList<GenExpenseHead>();
}

Moreover also simply your searchValue != null || searchValue != "" condition using string.IsNullOrWhiteSpace as I have used!

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
1

one way to solve it would be using the ?. (null propagation operator) and ?? (null coalescing operator):

expheadlist = expheadlist.Where(e => 
                    e.Name.ToLower().Contains(searchValue) || 
                    e.Description?.ToLower().Contains(searchValue) ?? false
                    ).ToList<GenExpenseHead>();

This says if Description is null then return false preventing the exception otherwise call .ToLower().Contains(searchValue)

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 1
    You cannot write `?.` (null conditional operator) and `??` (null coalescing operator) in `Where` clause as you wrote. it will throw `only, call, increment, decrement, await and new object expressions can be used as a statement.` error. – TanvirArjel Dec 26 '18 at 08:42
0

using ?. (null propagation operator) and ?? (null coalescing operator) for both fields such as

expheadlist = expheadlist.Where(e => 
                e.Name?.ToLower().Contains(searchValue) ?? false || 
                e.Description?.ToLower().Contains(searchValue) ?? false
                ).ToList<GenExpenseHead>();
Waiseman
  • 31
  • 3