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

前端之家收集整理的这篇文章主要介绍了c# – 如何修复“SqlException:将datetime2数据类型转换为日期时间数据类型导致超出范围的值.”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

sqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

我的代码是这样的:

  1. using (var contxt = new realtydbEntities())
  2. {
  3. var status = GetStatus();
  4.  
  5. var repIssue = new RepairIssue()
  6. {
  7. CreaterId = AuthorId,RepairItemDesc = this.txtDescription.Text,CreateDate = DateTime.Now,//here's the problem
  8. RepairIssueStatu = status
  9. };
  10.  
  11. contxt.AddObject("RepairIssues",repIssue);
  12. contxt.SaveChanges();
  13. }

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

如何让这段代码运行?

解决方法

您的问题的根源是C#DateTime对象比sql的smalldatetime类型“更大”.以下是对差异的概述: http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

所以你的选择真的是:

>将列类型从smalldatetime更改为datetime(或datetime2)>而不是使用EF,构建自己的sql命令(并且可以使用sqlDateTime)

猜你在找的C#相关文章