Nickson
Nickson

Reputation: 135

<inp>5__2 was null Exception in Net Core

I am receiving the error above. I am validating one field against another, basically after inputting the data into a text box, it is checked if it exists in another. I had set an if condition to ensure that if the data doesn't exist, then it returns to the same page for another try otherwise save. But the the error <inp>5__2 was null. is returned if the data doesn't exist.

Below is the code:

var inp = _ipacontext.Inpolicies.ToList().Where(x => x.PolicyNo == custView.Ppolicy).SingleOrDefault();
if (String.Equals(inp.PolicyNo, custView.Ppolicy))
{
custView.CID = Guid.NewGuid();
 _context.Add(customerData);
await _context.SaveChangesAsync();

return RedirectToAction("Complete", "Home");
}

return Redirect("/Home/Create");

custview.policyNo is the field entered from the form while inp.PolicyNo is the existing field being validated against.

Upvotes: 2

Views: 170

Answers (1)

Mariano Luis Villa
Mariano Luis Villa

Reputation: 497

If there's no element in _ipacontext that meets the condition in your Where, SingleOrDefault will return the default value (i.e., null for a reference type like a user-defined class). So this line:

var inp = _ipacontext.Inpolicies.ToList().Where(x => x.PolicyNo == custView.Ppolicy).SingleOrDefault();

... Might leave you with a null inp variable. In the next line you're doing inp.PolicyNo, i.e., calling a getter on a potentially null instance.

You could use a null-conditional to safely access your property:

if (String.Equals(inp?.PolicyNo, custView.Ppolicy)) //Note the ? after inp

That way, if inp is null, inp?.PolicyNo will return null, and your if will translate to: if(String.Equals(null, custView.Ppolicy)), which is false.

As a sidenote, String.Equals could be replaced by simply using ==. That way this wouldn't remind me of the legacy Java backend I have to maintain.

EDIT.

I just noticed that you're effectively doing the same comparison twice. Your piece of LINQ will return null if there's no matching element, so you could just do:

    var inp = _ipacontext.Inpolicies.ToList().Where(x => x.PolicyNo == custView.Ppolicy).SingleOrDefault();
    if (inp != null)
    {
      //Stuff
    }

Or even better clearer:

    if (_ipacontext.Inpolicies.Any(x => x.PolicyNo == custView.Ppolicy))
    {
      //Stuff
    }

Upvotes: 3

Related Questions