即使我已设置其可空值

时间:2016-03-06 14:36:56

标签: c# entity-framework

我正在尝试创建一个实体对象,但我对我的日期有一些问题它声称它没有值,即使我已将空白日期设置为1900.

DateTime startDate = rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdStarDate.SelectedDate.Value;

以下是正在使用它的保存功能。

    int id = Convert.ToInt32(Request.QueryString["id"]);


    _appointment = _dal.GetAppointMentByiD(id ,"");

    _appointment.CustomName = txtCustomerName.Text;
    DateTime startDate = rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdStarDate.SelectedDate.Value;

    DateTime endDate = rdEndDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdEndDate.SelectedDate.Value;

    _appointment.Start = startDate;
    _appointment.End = endDate;
    _appointment.Subject = txtSubject.Text;

    _appointment.notes = txtNotes.Text;
    _appointment.preferedContactNumber = txtContactNum.Text;
    _appointment.mobileNumber = txtMobileNumber.Text;
    _appointment.authUserName = Environment.UserName;
    _appointment.authCreatedDate = DateTime.Now;
        if (id == 0)
        {
            _dal.AddApointments(_appointment);
        }
    _dal.SaveChanges();
    rdMessaeBox.RadAlert("Appointment Saved", 200, 100, "Calander", "callBackFn", "myAlertImage.png");
  Response.Redirect("default.aspx");
  

.net中的错误是      可以为空的对象必须具有值。      描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中的起源位置的更多信息。

Exception Details: System.InvalidOperationException: Nullable object must have a value.

1 个答案:

答案 0 :(得分:0)

DateTime startDate = rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdStarDate.SelectedDate.Value;

此行说明: rdStartDate.SelectedDate.Value完全是1900/1/1时,然后(并且只有这样)将startDate设置为DateTime.Today
如果是null,则访问rdStartDate.SelectedDate.Value会向InvalidOperationException发送您收到的确切消息!

我认为你真正想要的是

DateTime startDate = (!rdStarDate.SelectedDate.HasValue ||
    rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1)) 
    ? DateTime.Today 
    : rdStarDate.SelectedDate.Value;

您声明 rdStarTime.SelectedValue设置为1900/1/1,但您没有显示该行,也没有显示异常的堆栈跟踪。因此,如果确实设置了该值,则可以引发异常的唯一其他可能性是rdEndDate.SelectedValue.Value的同一行。

P.S。:不应该是rdStartDate而不是rdStarDate吗?