c# - 使用 DateTime.Now 插入值时 SqlDateTime 溢出

标签 c# sql linq

最近我在尝试执行 db.SubmitChanges() 时遇到了很奇怪的错误:

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

关键是,我只使用 DateTime.Now 来设置对象中的属性,并且在调用 Response.Write(DateTime.Now.ToString()); 之后它显示 17-04-2013 18:03:13 应该是这样。

以前不会发生,现在功能总是中断。我完全无能为力 - 我的 SQL 服务器上的日期似乎没问题。

可能是什么原因造成的?

编辑

我认为这不会有帮助(在 IMO 中出现任何错误太简单了),但这是我的功能:

public bool ReportLogIn(int UserID, string IP, int Succeed ... ) {
    A_UserLoginHistory Report = new A_UserLoginHistory();

    Report.IP = IP;
    Report.UserID = UserID;
    Report.Status = Succeed;
    Report.Date = DateTime.Now; //the only DateTime field
    ...

    try {
        db.A_UserLoginRegistry.InsertOnSubmit(Report);
        db.SubmitChanges();
        return true;
    } catch (Exception e) {
        ErrorLog.AddError(e.ToString());
        return false;
    }
}

最佳答案

实际上问题是 SQL DateTime =/= C# Datetime

你需要改变两件事

  • 数据库将字段类型从 DateTime 更改为 DateTime2

  • 查询需要明确

    SqlCommand cmd = new SqlCommand("insertsomeDate", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@newDate", SqlDbType.DateTime2).Value = yourDate; //<- as example
    

您可以找到更多信息here , herehere

关于c# - 使用 DateTime.Now 插入值时 SqlDateTime 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065028/

相关文章:

mysql - SQL 连接以将主表中的值与子表值连接为一行中的不同列

c# - LINQ to Entities Union 抛出错误

c# - 如何查询这个 XML 文件?

c# - 在 C# 数组中查找元素的连续重复并更改元素

c# - 如何防止 ReSharper 在已编译的库中搜索?

c# - C#中如何执行sql select语句

mysql - 在 Mysql 事件中进行选择和更新

SQL 按列 1 "keep"按日期时间分组

.net - EF : Can I have single point for lambda to class instance conversion?

c# - 错误: Unable to connect to any of the specified MySQL hosts