0

sorry if my english is not good.

I am working in a view to do a search, I am using JSon to do the query,

When I get the data from the database using the next JSON:

Json(db.CertificationHeaders.ToList().Join(db.CertificationDetails, c => 
c.HeaderCertificationID, cd => cd.HeaderCertificationID, (c, cd) => new { c, 
cd })
.Where((d => (d.c.PlanID.ToString().Contains(planID)) && 
d.cd.InternalConsecutive.Contains(internalConsecutive) || 
d.cd.SecurityConsecutive.Contains(securityConsecutive) || 
d.c.RequestDate.Value.Year.ToString().Contains(year) || 
d.c.DateGrant.Contains(grantDate)))

everything goes well untill this part of the code:

d.cd.SecurityConsecutive.Contains(securityConsecutive)

when the info from the data base comes "null" I get a

NullReferenceExeption

I have been doing a research and the information says that this error comes when a value from database is null,so the question is: how can I avoid it?

1
  • I have a serious issue with people who have nothing better to do than go from post to post downvoting posts. Not civic-minded at all! Commented Aug 17, 2017 at 20:53

2 Answers 2

1

You have to filter out null instances. Replace:

d.cd.SecurityConsecutive.Contains(securityConsecutive)

With:

(d.cd.SecurityConsecutive != null && d.cd.SecurityConsecutive.Contains(securityConsecutive))

This first checks to see if SecurityConsecutive and only if it is not null does it call Contains. That is thanks to the && operator only checking the second operand if the first one is true. Wrapping it all up in parentheses makes the outer Where treat it as a single statement. It will be true only if both inner expressions (!= and Contains) are true.

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

1 Comment

@DannyFernández Glad I could help. Be sure to mark the answer as accepted, and best of luck
0

You need to put some more guard code into place. If you have the latest version of .NET, it becomes a bit easier to do:

Json(db.CertificationHeaders
    .ToList()
    .Join(db.CertificationDetails, c => c.HeaderCertificationID, 
         cd => cd.HeaderCertificationID, (c, cd) => new { c, cd })
    .Where((d => (d.c.PlanID?.ToString().Contains(planID)) && 
            d.cd.InternalConsecutive?.Contains(internalConsecutive) || 
            d.cd.SecurityConsecutive?.Contains(securityConsecutive) || 
            d.c.RequestDate?.Year.ToString().Contains(year) || 
            d.c.DateGrant?.Contains(grantDate)));

The ? syntax is called the null-conditional operator, and you can learn more about it here: https://msdn.microsoft.com/en-us/magazine/dn802602.aspx.

Hope this helps!

Comments

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.