使用LINQ to SQL SubmitChanges()时会导致SqlDateTime溢出的原因是什么?

时间:2009-09-29 18:00:12

标签: asp.net-mvc linq-to-sql

在我的代码中,我将多个对象添加到存储库中,我尝试在所有循环结束时一次运行存储库Save()函数,并在添加的每个对象之后调用它。但无论哪种方式,我仍然得到一个SqlDateTime溢出当存储库中的db.SubmitChanges().Save()...任何想法?

 SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

Source Error:

Line 155:        public void Save()
Line 156:        {
Line 157:            db.SubmitChanges();
Line 158:        }
Line 159:


Source File: C:\inetpub\wwwroot\Models\OrderRepository.cs    Line: 157


        foreach (string vol in volumes)
        {
            if (vol != "-1" && vol != "")
            {
                Product prod = orderRepository.getProductByVolumeID(System.Convert.ToInt32(vol));
                ProductVolume pvol = orderRepository.getProductVolumeByID(System.Convert.ToInt32(vol));

                OrderProduct oProd = new OrderProduct();
                oProd.OrderID = getOrder.OrderID;
                oProd.VolumeID = pvol.VolumeID;
                orderRepository.AddOrderProduct(oProd);


            }
        }

        foreach (string feat in features)
        {
            if (feat != "")
            {
                Product prod = orderRepository.getProductByID(System.Convert.ToInt32(feat));

                OrderFeature oFeat = new OrderFeature();
                oFeat.OrderID = getOrder.OrderID;
                oFeat.ProductID = prod.ProductID;
                orderRepository.AddOrderFeature(oFeat);


                featuresTotal += prod.UserIntervalPrice;
            }

        }

        totalTotal = volumeTotal + featuresTotal;
        orderRepository.Save();

2 个答案:

答案 0 :(得分:5)

基本上,问题是Sql DATETIME数据类型从1/1/1753开始,而日期时间.MinValue是1/1/0000(或类似的东西)。因此,如果不初始化日期属性,则会出现Sql溢出。

要修复的选项:

a)初始化DateTime somewheres。

b)切换sql以使用DATETIME2数据类型,该数据类型覆盖整个.NET DateTime值范围。 [仅限SQL 2008]

答案 1 :(得分:1)

您可以使用OnValidateSqlDateTime.MinValueSqlDateTime.MaxValue()部分方法中验证日期。