0

I have a scenario that I am getting the result properly .But i have to search it in that result.Here is my code.

if(productSearch.Keyword !=null || productSearch.Code!=null)
{
    var key = productSearch.Keyword;
    var cod = productSearch.Code;

    if (productSearch.Code != null)
    {
        var Selected_Result = result.Results.Where(s => s.Code.ToLower().Contains(cod.ToLower())).ToList();                     
        result.Results = Selected_Result;
    }
    else
    {
        var Selected_Result = result.Results.Where(s => s.Keyword.ToLower().Contains(key.ToLower())).ToList();                        
        result.Results = Selected_Result;
    }
}

But it gives following exception :

Object reference not set to an instance of an object on result.Results.Where(s => s.Code.ToLower().Contains(cod.ToLower())).ToList();

I know s => s.Code.ToLower() is coming NULL, but i dont know why, result has records. Thanks in advance.

6
  • s.Code is null in that case. Commented Dec 4, 2013 at 10:07
  • Looks like one of items in results has Code equal to null Commented Dec 4, 2013 at 10:07
  • Yes S.code is null, But how to get it. Commented Dec 4, 2013 at 10:08
  • productSearch.Code cannot be null.... but are you checking if result is null, more to the point result.code can be null eh. Commented Dec 4, 2013 at 10:11
  • Thx for time. Actually i was searching in wrong column. Commented Dec 4, 2013 at 10:17

1 Answer 1

4

If it's null in the query then chances are it's null in the DB. To be on the safe side you can use the null coalescing operator to make sure you have at least something to call ToLower on e.g.

result.Results.Where(s => (s.Code ?? "").ToLower().Contains(cod.ToLower()))
              .ToList();
Sign up to request clarification or add additional context in comments.

6 Comments

It's a string, it most certainly can be. If you mean it's a non-nullable at the DB side then, yeah, something's probably wrong with your mapping.
James wouldn't you rather use 'String.Empty'?
oh thx..I got my mistake.I actually searching in wrong column.
@Campl3r pretty sure EF doesn't support String.Empty. Regardless you aren't gaining much by using String.Empty over "" anyway.
@James EF does accept String.Empty No gain indeed, just a coding choice... I also prefer String.Empty, but have no religion
|

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.