开发者

System.InvalidOperationException must contain value for ViewModel

I have this in my controller:

MyTestViewModel asdf = new MyTestViewModel 
{
    SomeTestDate = _b.Get开发者_开发知识库SomeDate(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


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;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜