0

I have a JavaScript function that looks like this

<script type="text/javascript">

        function add() {
            var token = $("input[name='__RequestVerificationToken']", "#__AjaxAntiForgeryForm").val();

            var parts = [], partsqty = [];

            // Get all part ids and quantities and store them in arrays

            var partssel = document.getElementsByClassName("Part-select");
            var partsqtysel = document.getElementById('Part-qty').value;
            for (i = 0; i < partssel.length; i++) {
                parts[i] = partssel[i].options[partssel[i].selectedIndex].value;
                partsqty[i] = partsqtysel;
                if (partsqty[i] < 0) {
                    alert("Quantities can't be negative!");
                    return;
                }

            }
            alert("I am an alert box too!");
            $.ajax({
                type: "POST",
                url: "@IGT.baseUrl/JODetailsAjax/AddUnits",
                traditional: true,
                data: {
                    __RequestVerificationToken: token,
                    jo_id: @Model.Id,
                    addPart_id: parts,
                    addPart_qty: partsqty
                },
                success: function (data) {
                    if (data.success === "False") {
                        var errorMessage = data.Message;
                        alert("Error: " + errorMessage);
                        return;
                    }
             if(data.success === "True"){
                location.href = "../JobOrders/Details?id=@Model.Id";
             }
                },
                error: function (jqXHR, status, error) {
                    alert("Error:" + error);
                }
            });
        }

</script>

Which calls my 'AddUnits' function that looks like this

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult AddUnits(int jo_id, int[] addPart_id, float[] addPart_qty)
        {
            bool canCreate = true;
            string errors = "";

            for (int i = 0; i < addPart_id.Length; i++)
            {
                foreach (JODetails jod in db.JobOrders.Find(jo_id).JODetails)
                {                    
                    if (i < addPart_id.Length && addPart_qty[i] != 0 && jod.PartID == addPart_id[i])
                    {
                        jod.part_qty += addPart_qty[i];
                        addPart_id[i] = 0;
                        addPart_qty[i] = 0;
                    }
                }
                db.SaveChanges();

                if (i < addPart_qty.Length && addPart_qty[i] != 0)
                {
                    JODetails jODetails = new JODetails
                    {
                        JobOrderID = jo_id
                    };

                    // Only add a unit to the JODetails object if it's not null and has an id and quanitity specified              
                    if (i < addPart_id.Length && addPart_id[i] != 0 && addPart_qty[i] != 0)
                    {
                        jODetails.PartID = addPart_id[i];
                        jODetails.part_qty = addPart_qty[i];
                    }


                    JobOrder JO = db.JobOrders.Find(jODetails.JobOrderID);
                    JODetails jobOrderDetails = db.JODetails.Add(jODetails);
                    jobOrderDetails.JobOrder = JO;

                    Part JO_Part = db.Parts.Find(jODetails.PartID);
                  
                    if (JO_Part != null)
                    {
                        jODetails.part_qty = jODetails.part_qty == null ? 0 : jODetails.part_qty;
                        float qtyOrdered = jODetails.part_qty == null ? 0 : (float)jODetails.part_qty;
                        jobOrderDetails.dynamicPart_qty = qtyOrdered;
                    }

                    if (!canCreate)
                    {
                        var errorMessage = string.Join(",", errors);
                        var stock = new { success = "False", Message = errorMessage };
                        return Json(stock, JsonRequestBehavior.AllowGet);
                    }


                    db.JODetails.Add(jODetails);
                }
                
            }

            db.SaveChanges(); // error on this line

            JobOrder jobOrder = db.JobOrders.Find(jo_id);

            bool hasParts = false;


            foreach (JODetails jod in jobOrder.JODetails)
            {
                if (jod.Parts != null && jod.part_qty > 0)
                    hasParts = true;
            }

            ViewBag.hasParts = hasParts;

            var result = new { success = "True" };
            return Json(result);

        }

But everytime it runs through the method theres an error at the db.SaveChanges(); which says

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

As you can see nothing in my code is even referencing a date so I'm not sure why this problem is occurring? I have searched for answers on the internet but everybody seems to have been dealing with dates when they experienced the issue.

Any help is appreciated.

zealous
  • 7,336
  • 4
  • 16
  • 36
  • Java you have a string while the sql you have a DateTime object. So you have to parse the string to a DateTime object. – jdweng Jul 17 '20 at 15:58
  • @jdweng parse what string? –  Jul 17 '20 at 16:00
  • Does table in database have a DATE column. You may need to add the missing date. The DateTime cannot be null. – jdweng Jul 17 '20 at 17:07

2 Answers2

0

To debug the problem most effeciently first check your database Table.

Now check the following cases:

  • Does it contain Date columns?
  • If yes are the columns nullable?

In case if your DB Table has non-nullable columns you may encounter an error when trying to save new data, which doesn't contain information for the Date column (i.e. null value) or it might want to accept a default value for the Date column with wrong formatting.


A few general suggestions for the above code:

  • You don't need to have so many db.SaveChanges() calls, for me at the first look the most first and the last calls for saving changes are redundant.
  • Prefer using foreach statement instead of for especially when there is no need to use the index for specific operations.
  • Don't use complex expressions inside iterations, sometimes they can produce unpredicted results or trigger exceptions in case of data change.
Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
0

C# DateTime object is "bigger" than SQL's smalldatetime type How to fix "SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value."