开发者

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.Subtra开发者_开发百科ct((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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜