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?

6
  • 2
    Is that the exact line where the exception is thrown? If not please expand the code and add a stack trace. Commented Aug 24, 2011 at 15:21
  • yes I put a breakpoint there, and when the application reaches that point, throws an exception. Commented Aug 24, 2011 at 15:26
  • Check out this question: stackoverflow.com/questions/1896185/… Commented Aug 24, 2011 at 15:30
  • 1
    There is something between the { .... } throwing the exception. If you are using a nullable DateTime, make sure you check for .HasValue. Commented Aug 24, 2011 at 15:30
  • @IAbstract in {....} I just read and copmare loginDate in this manner : TimeSpan span = DateTime.Now.Subtract((DateTime)site.logindDate ); Commented Aug 24, 2011 at 15:45

2 Answers 2

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.

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

Comments

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.

2 Comments

that wouldn't explain the problem since OP specifically does a null check on site
I am sure that always on element returned by list, but I will use single and test the application again. [Edited] Using Single() does not work.

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.