使用DateTime.Now插入值时,SqlDateTime溢出 [英] SqlDateTime overflow when inserting value with DateTime.Now
问题描述
最近我在尝试执行db.SubmitChanges()
时遇到了很奇怪的错误:
Lately I have quite odd error while trying to do db.SubmitChanges()
:
SqlDateTime溢出.必须在1/1/1753 12:00:00 AM和12/31/9999 11:59:59 PM之间.
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
.
The point is, I only use DateTime.Now
to set property in my object, and after calling Response.Write(DateTime.Now.ToString());
it shows 17-04-2013 18:03:13
as it should be.
这不是以前发生的事情,现在该功能始终会中断.我完全一无所知-我的SQL Server上的日期似乎还可以.
It was not happening earlier, and now the function always breaks. I'm completely clueless - date on my SQL server seems to be ok.
可能是什么原因造成的?
What may cause it?
修改
我认为这没有帮助(太简单了,IMO中没有任何错误),但是有我的功能:
I don't think it would help (it just too simple to have any errors IMO), but there's my function:
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
actually the problem is SQL DateTime
=/= C# Datetime
您需要更改2件事
-
数据库将字段类型从
DateTime
更改为DateTime2
查询您需要明确
SqlCommand cmd = new SqlCommand("insertsomeDate", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@newDate", SqlDbType.DateTime2).Value = yourDate; //<- as example
这篇关于使用DateTime.Now插入值时,SqlDateTime溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!