开发者

MVC Update Error: datetime2

A bit of background to my issue - I've inherited a large C# MVC application, and I'm currently making a change to the main process in the app.

So originally, the user would upload an item, and that would be that. Now however, the user can select a checkbox in order to have the item delivered. If this checkbox is selected, the Delivery table is populated with the relevant details.

Here is the POST action in my Items controller for when the user originally uploads the item details:

        [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);
        }

This works fine, and achieves the desired result. However, I am a little stuck on modifying the update action for in the Items controller. Here is what I have so far:

[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);
}

Notice how this is slightly different and uses the UpdateItemDetails() to update the database. I was unsure what to do here as I do need to collect formvalues t开发者_如何学Co insert into the Delivery database. Here is 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();
        }
    }

The code working as above, throws the following error when I try to update the details:

System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

This error is thrown at ctn.SaveChanges() in the update action.

So I suppose my first question is how to overcome this error, however without making changes that will affect the AddItemDetails action. My second question then would be, if that error was cleared up, would this be a correct way to go about updating?

I'd be very grateful for any pointers. If any more info is needed, just ask.

Thanks :)


I was looking into your error and found this answer to another question that gives a little more information about the DATETIME and DATETIME2 data types.

DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2 support 0001/1/1 through eternity.

If you check the data that is being submitted do you see anything anomalous? Do you have a date property in your item class that is being set to some default value that is invalid for the DATETIME field?


It looks like one of the dates in the object you are trying to save is DateTime.MinValue. It could be the submission date for example. Check your form data to see if the value is being updated ofmr the client correctly and go from there.


I have this issue currently because if someone mistakenly forgets a slash (e.g. 1/189 when they meant 1/1/89), TryUpdateModel() updates the model without error, translating it to the .NET DateTime of "1/1/0189".

But then the Save crashes with the "conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value".

So wow do I catch this before the Save?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜