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

时间:2012-05-08 08:58:38

标签: c# asp.net entity-framework webforms

  

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

我的代码是这样的:

        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 的列。

如何运行此代码?

6 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:5)

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

所以你的选择真的是:

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

答案 2 :(得分:1)

SqlDateTime将允许您做您需要的事情。

答案 3 :(得分:1)

将此添加到您的模型类:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
    }

答案 4 :(得分:0)

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

答案 5 :(得分:0)

检查您的迁移内容。我是这样改变我的模特的”

  

公共DateTime? CreationDate {get;组; }

然后添加新的迁移并最终运行更新数据库