如何修复“SqlException:将datetime2数据类型转换为日期时间数据类型导致超出范围的值。”

SqlException:将datetime2数据类型转换为datetime数据类型会导致超出范围的值。

我的代码是这样的:

using (var contxt = new realtydbEntities()) { var status = GetStatus(); var repIssue = new RepairIssue() { CreaterId = AuthorId, RepairItemDesc = this.txtDescription.Text, CreateDate = DateTime.Now,//here's the problem RepairIssueStatu = status }; contxt.AddObject("RepairIssues", repIssue); contxt.SaveChanges(); } 

CreateDate属性映射到类型为smalldatetime的列。

如何让这段代码运行?

您的问题的根源是C#DateTime对象比SQL的smalldatetime类型“更大”。 以下是对差异的概述: http : //www.karaszi.com/SQLServer/info_datetime.asp

所以你的选择真的是:

  1. 将列类型从smalldatetime更改为datetime(或datetime2)
  2. 而不是使用EF,构建自己的SQL命令(并且您可以使用SqlDateTime)

我有相同的exception,但这是因为不可为空的datetime属性采用最小日期时间值。 这不是DB的小时间,但C#的最小日期时间超过了SQL的最小日期时间限制。 解决方案很明显,正确设置日期时间。 顺便说一句,代码不是我的,这就是为什么我不知道那个属性:)

SqlDateTime将允许您执行所需的操作。

我收到此错误是因为我在我的SQL表和应用程序中添加了一个datetime列而没有删除旧数据。 我发现我可以更新新记录; 但是,当在其中一个上尝试更新时,添加字段之前的表中的记录会引发此错误。