System.Data.SqlTypes.SqlTypeException:SqlDateTime溢出

Cla*_*ear 5 .net c# sql-server sql-server-2008

我正在使用C#.net和SQL Server 2008.

尝试在我的项目中运行测试单元时出现以下错误.

   System.Data.SqlTypes.SqlTypeException:
   SqlDateTime overflow. Must be between
   1/1/1753 12:00:00 AM and 12/31/9999
   11:59:59 PM..
Run Code Online (Sandbox Code Playgroud)

数据库表

Column Name: createddate 
Type: datetime
Default Value: (getdate())
Allow Nulls: No.
Run Code Online (Sandbox Code Playgroud)

我不想在我的INSERT查询中插入createddate.

当我手动将一些数据输入数据库表时,我收到以下错误:

   The row was successfully committed
   to the database. However, a problem
   occurred when attempting  to retrieve
   the data back after commit. Because
   of this the displayed data within the
   row is read-only. To fix this
   problem, please re-run the query.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我收到这个错误,找不到有这个问题的人.有人可以帮忙吗?

mar*_*c_s 7

马特最有可能走上正轨.您已为列定义了默认值 - 但是,只有在数据库中实际插入表中的内容时才会生效.

当您进行单元测试时,如您所说,您很可能将DateTime变量初始化为某个(或者不是 - 然后它将是DateTime.MinValue,即01/01/0001),然后将其发送到SQL Server并且此值超出了SQL Server上DATETIME的有效范围(因为错误明确指出).

所以你需要做的是在你的.NET单元测试中添加一行来将DateTime变量初始化为"DateTime.Today":

DateTime myDateTime = DateTime.Today
Run Code Online (Sandbox Code Playgroud)

然后将其插入SQL Server.

或者:您可以更改SQL INSERT语句,以便它不会为该列插入值 - 它现在看起来像它,它确实这样做(并尝试将其插入 - 对于SQL Server - 无效日期到表中).如果您未在INSERT中指定该列,则列默认值getdate()将启动并将今天的日期插入列中.