Nullable object must have a value.

S

shapper

Hello,

I am trying to define a value for a statistic as follows:

FilesPerMonth = db.Files.Count() /
(float)((DTH.Span(DI.Month, db.Files.Min(f =>
f.CreatedAt), DateTime.Now) ?? 1) == 0 ? 1 :
DTH.Span(DI.Month, db.Files.Min(f =>
f.CreatedAt), DateTime.Now).Value),

FilesPerMonth is a float

Basically, I check if DTH.Span returns null ... if it does I define a
default value = 1.
If not I check if the value is 0. If yes I give it the value 1 to
prevent division by 0.
Otherwise I use the returned value.

my DTH.Span function is:

public static long? Span(DateInterval interval, DateTime? from,
DateTime? to)

I am using this inline code because I am using this on a Linq Query.

Does anyone knows what I am doing wrong. I chenged my code many times
but I keep having the same problem:

"Nullable object must have a value."

I though I had preview all possible situations on my code but I am
missing something.

Thank You,
Miguel
 
M

Marc Gravell

In the first test, you use null-coalescing (?? 1) - but you don't do
this in the second. So if the thing *is* null, the first test fails
(since null ?? 1 is not zero, so the second version is evaluated which
yields null. I suspect you want to use null-coalescing in the second
version, too.

I don't know if your link provider supports it, but you might be able
to use .GetValueOrDefault(1) to do this (in both cases).

Marc
 
S

shapper

In the first test, you use null-coalescing (?? 1) - but you don't do
this in the second. So if the thing *is* null, the first test fails
(since null ?? 1 is not zero, so the second version is evaluated which
yields null. I suspect you want to use null-coalescing in the second
version, too.

I don't know if your link provider supports it, but you might be able
to use .GetValueOrDefault(1) to do this (in both cases).

Marc

Thanks! Didn't know about GetValueOrDefault. Was reading about it.
Really useful.
I solved my problem without it but I started using it because it
simplifies it a lot.

Thank You!
Miguel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top