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

Lem*_*urr 13 c# sql linq

最近我尝试做的时候有很奇怪的错误db.SubmitChanges():

SqlDateTime溢出.必须在1/1/1753 12:00:00 AM和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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Wii*_*axx 5

其实问题是 SQL DateTime=/= C# Datetime

你需要改变两件事

  • 数据库将字段类型从 更改DateTimeDateTime2

  • 您需要明确的查询

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

您可以在此处此处此处找到更多信息