【问题标题】:MVC Update Error: datetime2MVC 更新错误:datetime2
【发布时间】:2011-12-16 01:16:42
【问题描述】:

我的问题的一些背景知识 - 我继承了一个大型 C# MVC 应用程序,我目前正在更改应用程序中的主进程。

所以最初,用户会上传一个项目,就是这样。然而,现在,用户可以选择一个复选框以交付该项目。如果选中此复选框,则交付表将填充相关详细信息。

这是我的 Items 控制器中用户最初上传项目详细信息时的 POST 操作:

        [HttpPost]
        public ActionResult AddItemDetails(Int64? itemId, Item item, FormCollection formValues)
        {
            if (formValues["cancelButton"] != null)
            {
                return RedirectToAction("Index");
            }

            if (formValues["backButton"] != null)
            {
                return RedirectToAction("AddItemStart");
            }

            string ImageGuid = formValues["ImageGUID"];
            ViewData["Image_GUID"] = ImageGuid;

            if (item.ImageID == null && String.IsNullOrEmpty(ImageGuid))
            {
                ModelState.AddModelError("Image", "Image is required.");
                ViewData["Image"] = "Image is required.";
            }

            if (ModelState.IsValid)
            {
                item.SubmissionState = -1; // Unsubmitted;

                /**********************ADDED 25/1/2011**************************/
                item.ProductCode = formValues["ProductCode"];
                item.Name = formValues["Name"];


                string deliverySelection = formValues["deliverySelection"];

                if (deliverySelection == "on")
                {
                    item.DeliverySelection = "Yes";

                    Delivery c = new Delivery()
                    {
                        ProductCode = formValues["ProductCode"],
                        Name = formValues["Name"],
                        PhoneNo = formValues["PhoneNo"],
                        Address = formValues["Address"],
                        SubmissionDate = System.DateTime.Now
                    };

                    item.Delivery = c;
                }
                else
                {
                    item.DeliverySelection = "No";
                }

                /*****************************END*******************************/
                if (itemId.HasValue)
                {
                    UpdateItemDetails(item, ImageGuid, this);
                }
                else
                {
                    titleId = ItemServices.AddItem(item, ImageGuid);
                }

                return RedirectToAction("AddSubItemDetails", new { itemId = item.ItemID });
            }

            return View(item);
        }

这工作正常,并达到了预期的结果。但是,我有点坚持修改 Items 控制器中的更新操作。这是我目前所拥有的:

[HttpPost]
public ActionResult UpdateItemDetails(Int64 itemId, Item item, FormCollection formValues)
{
    if (formValues["cancelButton"] != null)
    {
        return RedirectToAction("View", new { itemId = itemId });
    }

    string image = formValues["ImageGUID"];
    ViewData["Image_GUID"] = ImageGuid;

    if (item.ImageID == null && String.IsNullOrEmpty(ImageGuid))
    {
        ModelState.AddModelError("Image", "Image is required.");
    }

    if (ModelState.IsValid)
    {
        //**********************Added 31.01.2011****************************//
     using (ModelContainer ctn = new ModelContainer())
     {
            string DeliverySelection = formValues["deliverySelection"];

            if (deliverySelection == "on")
            {
                item.DeliverySelection = "Yes";

                Delivery c = new Delivery()
            {
                ProductCode = formValues["ProductCode"],
                Name = formValues["Name"],
                PhoneNo = formValues["PhoneNo"],
                    Address = formValues["Address"],
                SubmissionDate = System.DateTime.Now
            };

                    ctn.Delierys.AddObject(c);

                item.Delivery = c;

            }
            else
            {
                item.DeliverySelection = "No";
            }


        ctn.AddToItems(item);
        ctn.SaveChanges();

        UpdateItemDetails(item, ImageGuid, this);
        return RedirectToAction("View", new { itemId = itemId });
    }

    return View("UpdateItemDetails", MasterPage, item);
}

请注意这略有不同,并使用 UpdateItemDetails() 来更新数据库。我不确定在这里做什么,因为我确实需要收集表单值以插入到 Delivery 数据库中。这是UpdateItemDetails:

 private void UpdateItemDetails(Item item, string ImageFileGuid, ItemsController controller)
    {
        using (ModelContainer ctn = new ModelContainer())
        {
            Item existingData = ItemServices.GetCurrentUserItem(item.ItemID, ctn);
            controller.UpdateModel(existingData);

            existingData.UpdatedBy = UserServices.GetCurrentUSer().UserID;
            existingData.UpdatedDate = DateTime.Now;

            // If there is a value in this field, then the user has opted to upload
            // a new cover.
            //
            if (!String.IsNullOrEmpty(ImageFileGuid))
            {
                // Create a new CoverImage object.
                //
                byte[] imageBytes = FileServices.GetBytesForFileGuid(Guid.Parse(ImageFileGuid));

                Image newImage = new Image()
                {
                    OriginalCLOB = imageBytes,
                    ThumbnailCLOB = ImageServices.CreateThumbnailFromOriginal(imageBytes),
                    HeaderCLOB = ImageServices.CreateHeaderFromOriginal(imageBytes),
                    FileName = "CoverImage"
                };

                existingData.Image = newImage;
            }

            ctn.SaveChanges();
        }
    }

如上运行的代码,当我尝试更新详细信息时抛出以下错误:

System.Data.SqlClient.SqlException: datetime2 数据的转换 类型为日期时间数据类型导致 在一个超出范围的值。这 语句已终止。

此错误在更新操作中的 ctn.SaveChanges() 处引发。

所以我想我的第一个问题是如何克服这个错误,但是不进行会影响 AddItemDetails 操作的更改。那么我的第二个问题是,如果该错误被清除,这是否是进行更新的正确方法?

我将非常感谢任何指点。如果需要更多信息,请询问。

谢谢:)

【问题讨论】:

    标签: c# asp.net-mvc-2 entity-framework-4 linq-to-entities


    【解决方案1】:

    我正在调查您的错误,发现 this answer 另一个问题提供了有关 DATETIME 和 DATETIME2 数据类型的更多信息。

    DATETIME 支持 1753/1/1 到 “永恒”(9999/12/31),而 DATETIME2 支持 0001/1/1 到 永恒。

    如果您检查正在提交的数据,您是否发现任何异常?您的项目类中是否有一个日期属性被设置为某个对 DATETIME 字段无效的默认值?

    【讨论】:

      【解决方案2】:

      看起来您要保存的对象中的日期之一是 DateTime.MinValue。例如,它可能是提交日期。检查您的表单数据以查看客户端的值是否正确更新并从那里开始。

      【讨论】:

        【解决方案3】:

        我目前有这个问题,因为如果有人错误地忘记了斜线(例如 1/189,他们的意思是 1/1/89),TryUpdateModel() 会更新模型而不会出错,将其转换为 .NET DateTime 的“1/ 1/0189"。

        但随后保存崩溃,“将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围”。

        那么哇,我要在保存之前捕捉到这个吗?

        【讨论】:

        • 上面链接的帖子说“检查日期的年份 - 如果它在 1753 之前,你需要将它更改为 1753 之后的东西”,但认真吗? TryUpdateModel 的全部意义在于,您不必对每个字段进行硬编码验证检查。必须有更好的方法。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-21
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多