tags:

views:

20

answers:

1

Hello

I have this in my controller:

MyTestViewModel asdf = new MyTestViewModel 
{
    SomeTestDate = _b.GetSomeDate(SomeID).Value,
    SomeDate2 = SomeDate2.Value,
    SomeDate3 = SomeDate3.Value
    };

in the function "GetSomeDate" I have:

var x = c.ExecuteScalar();

return x as DateTime?;

And I get InvalidOperationException that object must contain value, when function returns null, which it should be able to.

What might be wrong here?

/M

+1  A: 

Before calling the getter of the Value property you must check if the nullable type contains a value or you will get an exception:

var date = _b.GetSomeDate(SomeID);
MyTestViewModel asdf = new MyTestViewModel 
{
    SomeTestDate = date.HasValue ? date.Value : DateTime.MinValue,
    SomeDate2 = SomeDate2.Value,
    SomeDate3 = SomeDate3.Value
};

Here's the relevant source code of the getter (extracted with Reflector):

public T get_Value()
{
    if (!this.HasValue)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue);
    }
    return this.value;
}
Darin Dimitrov