1

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?

IAbstract
  • 19,551
  • 15
  • 98
  • 146
Babak Fakhriloo
  • 2,076
  • 4
  • 44
  • 80

2 Answers2

2

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.

IAbstract
  • 19,551
  • 15
  • 98
  • 146
0

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.

Evren Kuzucuoglu
  • 3,781
  • 28
  • 51