最近我在尝试执行 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
关于c# - 使用 DateTime.Now 插入值时 SqlDateTime 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065028/