Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

nullable object must have a value in Linq

I use following Linq To Entitiy To get the first and only record of my 'siteconfig' Entity :

var site = unitofwork.SiteConfigRepository.Get().FirstOrDefault();

But when my application comes to the following code, throws 'nullable object must have a value' :

if (site!= null) { TimeSpan span = DateTime.Now.Subtract((DateTime)site.logindDate ); }

And the only nullable type in my entity is a property called logindDate and is of type DateTime.

Any one help me out?

Upvotes: 1

Views: 5736

Answers (2)

IAbstract
IAbstract

Reputation: 19881

Try something like this:

if (site!= null) 
{ 
    if (site.loginDate.HasValue)
    { TimeSpan span = DateTime.Now.Subtract((DateTime)site.logindDate.Value ); }
}

You are not checking for a null loginDate and I suspect that may be the problem. Remember, when you have a nullable type, you need to check for HasValue, and then get the value from the Value property.

Upvotes: 2

Evren Kuzucuoglu
Evren Kuzucuoglu

Reputation: 3885

IEnumerable.FirstOrDefault() returns the first element of the enumerable, or default(T) (which is generally null, unless T is a value type) if there is no element in the list. Most probably your Get() returns an empty enumerable.

On a related matter (if indeed it is what happens), if you're sure that there is always one and only one element returned by a list, you should use Single() (because then you will have an exception thrown at that line) or test it against null just after the FirstOrDefault(). I think it's best having exceptions throwing or handling at the source of the unexpected behavior, and not several lines later.

Upvotes: 0

Related Questions