Wednesday, October 12, 2011

LINQ Error "Nullable object must have a value"

PROBLEM: You get a runtime error when one of your LINQtoSQL queries runs which says "Nullable object must have a value".

SOLUTION: This one gets me every time... you've most likely got some logic which says something alone the lines of "if the value is either null or equals blah"... the problem is that with LINQ unlike your normal C# code, it will try and convert/evaluate both parts of the statement and hence result in a null error. The quick solution is to use a ternary operator and make sure you don't call anything on the nullable object e.g. with a DateTime? object don't explicitly call .value on it. Here is an example:


GOOD:

(competition.CompetitionEndDate.HasValue ? competition.CompetitionEndDate < DateTime.Today : false)

BAD:

(competition.CompetitionEndDate == null || competition.CompetitionEndDate.Value < DateTime.Today)

This comes up a lot... here are a few posts which might explain it better than me:

http://peetbrits.wordpress.com/2008/10/18/linq-breaking-your-logic/
http://msdn.microsoft.com/en-us/library/bb882535.aspx



No comments:

Post a Comment