【问题标题】:SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM in web apiSqlDateTime 溢出。必须在 web api 中的 1/1/1753 12:00:00 AM 和 12/31/9999 11:59:59 PM 之间
【发布时间】:2013-03-25 11:48:54
【问题描述】:

我正在尝试在 asp.net 上使用 c# 在 web api 中构建 post 方法 mvc 4.每当我使用提琴手向这个api发布价值时,我都会得到 以下错误:

SqlDateTime 溢出。必须在 1753 年 1 月 1 日凌晨 12:00:00 到 12/31/9999 晚上 11:59:59

我已经在我的 Web API 控制器中编写了以下代码。我也有 创建了数据访问层来访问数据库中的数据

public HttpResponseMessage PostMsg(MsgModel item)
    {
        if (ModelState.IsValid && item!=null)
        {
            using (dc = new MsgDataContext())
            {
                var dbMsg = new Msg() 
                {
                 Msg_Title= item.Msg_Title,
                 Msg_Date = item.Msg_Date,                    
                };                  
                dc.Msgs.InsertOnSubmit(dbMsg);
                dc.SubmitChanges();// Getting the above error at this line of code

                var response = Request.CreateResponse<MsgModel>(HttpStatusCode.Created, item);
                string uri = Url.Link("DefaultApi", new { id = dbMsg.Msg_Id});
                response.Headers.Location = new Uri(uri);
                return response;
            }
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

    }

I am posting the following request body from fiddler by executing the
url http://localhost:65070/api/signup Request Body {
'Msg_Title':"our first msg", 'Msg_Date':"2012/02/23T00:00:00"}

【问题讨论】:

  • 调试你的方法我猜item.Msg_Date是DateTime.Min。或者您在 Msg 上有一些额外的 DateTime 字段,您没有填写。

标签: asp.net sql-server-2008 asp.net-mvc-4 asp.net-web-api


【解决方案1】:

错误本身告诉解决方案-

您分配的 DateTime 值不在这两个日期之间。只需在插入数据库之前检查日期。如果日期小于 1/1/1753,则传递 DateTime.MinValue,如果日期大于 12/31/9999,则传递 DateTime.MaxValue

【讨论】:

  • 不,如果您按照此处的说明进行操作,您将收到此错误。我知道这是一个事实,因为这是我调试到的看似合乎逻辑的代码。
【解决方案2】:

您传递的日期值'Msg_Date':"2012/02/23T00:00:00" 未正确解析(作为“已知”日期字符串)-它没有时区/不匹配任何“已知”date format

DateTime.TryParse

【讨论】:

    【解决方案3】:

    您的问题是您正在将字符串解析为 DateTime 对象。如果Msg_Date 是 DateTime 对象,C sharp 将尝试隐式转换。如果失败,将返回 null。但是数据库中的 DateTime 对象的 null 值是不允许的,因此会出现此异常。在将实体保存到数据库之前进行一些调试。找到合适的日期格式,因为这似乎是您的问题。 查看this 的帖子,或阅读一些documentation

    【讨论】:

      【解决方案4】:

      使用SqlTypes.SqlDateTime.MinValue 而不是DateTime.MinValue 为我解决了这个问题。如果您已经在代码中使用DateTime 对象,则可以使用SqlTypes.SqlDateTime.MinValue.Value

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        • 2017-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多