Danny Fernández
Danny Fernández

Reputation: 11

How to validate null values on linq

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?

Upvotes: 0

Views: 81

Answers (2)

code4life
code4life

Reputation: 15794

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!

Upvotes: 0

steliosbl
steliosbl

Reputation: 8921

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.

Upvotes: 1

Related Questions