0

I am new to asp.net mvc. How can I automatically generate new Guid inside of foreach loop? I am using List<Expense> in view model and GUID as PrimaryKey, how I insert a multiple row from datatable to database insertion?

Here is my view model. I can insert a single row data, but if I insert more than one row data, it will show the error like :

Violation of PRIMARY KEY constraint 'PK__Expense__EBE72675160F4887'. Cannot insert duplicate key in object 'dbo.Expense'.\r\nThe statement has been terminated.

 public System.Guid MaintenanceId { get; set; }
    public System.Guid ExpenseSummaryId { get; set; }
    public string BillNo { get; set; }
    public Nullable<System.DateTime> BillDate { get; set; }
    public string VechicleNo { get; set; }
    public string ServiceType { get; set; }
    public Nullable<double> Amount { get; set; }
    public string Reason { get; set; }
    public Nullable<System.Guid> UserRightsId { get; set; }
    public Nullable<System.Guid> EmployeeId { get; set; }
    public string ProviderName { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string ProviderCity { get; set; }
    public string ProviderState { get; set; }
    public string ProviderCountry { get; set; }
    public string Pincode { get; set; }
    public int Sno { get; set; }
    public Nullable<bool> IsActive { get; set; }
    public Nullable<bool> IsDeleted { get; set; }
    public Nullable<System.DateTime> CreatedDate { get; set; }
    public Nullable<System.DateTime> EditedDate { get; set; }
    public Nullable<System.DateTime> LastActiveOn { get; set; }
    public Nullable<System.Guid> RowID { get; set; }
    public Nullable<System.Guid> CreatedSessionID { get; set; }
    public Nullable<System.Guid> EditedSessionID { get; set; }
    public Nullable<bool> OfflineMode { get; set; }
    public Nullable<System.Guid> OfflineID { get; set; }

    public List<Expense> Expenses { get; set; }
    public virtual Employee Employee { get; set; }
    public virtual UserRight UserRight { get; set; }

Here is My Controller

  public JsonResult SaveOrder(TruckVM TVM)
    {
        bool status = false;
      if (ModelState.IsValid)
        {
         using (TestDBEntities db = new TestDBEntities())
            {
              var guid = Guid.NewGuid();
              maintenance ObjMaintenance = new maintenance 
                { 
                 MaintenanceId=guid,
                 BillNo=TVM.BillNo,
                 BillDate=TVM.BillDate,
                 Amount=TVM.Amount
                 };                   

                foreach (var i in TVM.Expenses)
                {
                    ObjMaintenance.Expenses.Add(i);

                }

                db.maintenances.Add(ObjMaintenance);
                //db.serviceproviders.Add(ObjServiceProvider);
                db.SaveChanges();
                status = true;
            }
        }
        else
        {
            status = false;
        }
        return new JsonResult { Data = new  { status = status } };
    }`   

here is my view

 $(document).ready(function () {
        var orderItems = [];
        $('#add').click(function () {
            var isValidItem = true;
            
       
            if ($('#Particulars').val().trim() == '') {
                isValidItem = false;
                $('#Particulars').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#Particulars').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#qty').val().trim() != '' && !isNaN($('#qty').val().trim()))) {
                isValidItem = false;
                $('#qty').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#qty').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#unitprice').val().trim() != '' && !isNaN($('#unitprice').val().trim()))) {
                isValidItem = false;
                $('#unitprice').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#unitprice').siblings('span.error').css('visibility', 'hidden');
            }
            //Add item to list if valid
            if (isValidItem) {
                orderItems.push({
                  
                    Particulars: $('#Particulars').val().trim(),
                    qty: parseInt($('#qty').val().trim()),
                    unitprice: parseFloat($('#unitprice').val().trim()),
                    TotalAmount: parseInt($('#qty').val().trim()) * parseFloat($('#unitprice').val().trim())

                });

                //Clear fields
                $('#Particulars').val('').focus();
                $('#qty').val('')
                $('#unitprice').val('')
                

            }

            GeneratedItemsTable();
        });

        $('#submit').click(function () {
            //validation of order
            var isAllValid = true;
            if (orderItems.length == 0) {
                $('#orderItems').html('<span style="color:red;">Please add order items</span>');
                isAllValid = false;
            }

            if ($('#BillNo').val().trim() == '') {
                $('#BillNo').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#BillNo').siblings('span.error').css('visibility', 'hidden');
            }

            if ($('#BillDate').val().trim() == '') {
                $('#BillDate').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#BillDate').siblings('span.error').css('visibility', 'hidden');
            }

            //Save if valid
            if (isAllValid) {
                var data = {
                    BillNo: $('#BillNo').val().trim(),
                    BillDate: $('#BillDate').val().trim(),
                    Amount: $('#Amount').val().trim(),
                    Expenses: orderItems
                }

                $(this).val('Please wait...');

                $.ajax({
                    url: '/VechicleMaintenance/SaveOrder',
                    type: "POST",
                    data: JSON.stringify(data),
                    dataType: "JSON",
                    contentType: "application/json",
                    success: function (d) {
                        //check is successfully save to database 
                        if (d.status == true) {
                            //will send status from server side
                            alert('Successfully done.');
                            //clear form
                            orderItems = [];
                            $('#BillNo').val('');
                            $('#BillDate').val('');
                            $('#orderItems').empty();
                        }
                        else {
                            alert('Failed');
                        }
                        $('#submit').val('Save');
                    },
                    error: function () {
                        alert('Error. Please try again.');
                        $('#submit').val('Save');
                    }
                });
            }

        });

        function GeneratedItemsTable() {
            if (orderItems.length > 0) {
                var $table = $('<table/>');
                $table.append('<thead><tr><th>Particulars</th><th>qty</th><th>unitprice</th><th>TotalAmount</th></tr></thead>');
                var $tbody = $('<tbody/>');
                $.each(orderItems, function (i, val) {
                    var $row = $('<tr/>');
                   
                    $row.append($('<td/>').html(val.Particulars));
                    $row.append($('<td/>').html(val.qty));
                    $row.append($('<td/>').html(val.unitprice));
                    $row.append($('<td/>').html(val.TotalAmount));
                    $tbody.append($row);
                });
                $table.append($tbody);
                $('#orderItems').html($table);
            }
        }

     


    });
 <table width="100%">
                <tr>
                   
                    <td>Particulars</td>
                    <td>qty</td>
                    <td>unitprice</td>
                    <td>&nbsp;</td>
                </tr>
                
              <tr>
                    <td>
                        <input type="text" id="Particulars" />
                        <span class="error">Item name required</span>
                    </td>
                    <td>
                        <input type="text" id="qty" />
                        <span class="error">Valid quantity required</span>
                    </td>
                    <td>
                        <input type="text" id="unitprice" />
                        <span class="error">Valid rate required</span>
                    </td>
                     <td>
                        <input type="button" id="add" value="add"    />
                    </td>
                </tr>
            </table>
            <div id="orderItems" class="tablecontainer">

            </div>
            <div style="padding:10px 0px; text-align:right">
                <input id="submit" type="button" value="Save" style="padding:10px 20px" />
            </div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Felish Anand
  • 35
  • 1
  • 10
  • Your table key is auto-generated or you should assign the key value yourself? If it is auto-generated, you should not assign any value to it, else you can set the key value using `Guid.NewGuid()` – Reza Aghaei Dec 04 '15 at 05:07
  • 1
    You need to create a new `Guid` in the `foreach (var i in TVM.Expenses)` and assign it to each`Expenses` object (just as your doing for the `ObjMaintenance` object) –  Dec 04 '15 at 05:09
  • #Reza Aghaei : My Table is Not Auto Generated,I am assigned Guid.NewGuid ,But it will work for single row ,If i inserting More than one row it will showing Error.So that only i am posting entire code , i don't know Where i could make mistake. – Felish Anand Dec 04 '15 at 05:16
  • #Stephen Muecke: Can u explain elaborately. I Can't understand, i am almost done what u said.but it still happend Error – Felish Anand Dec 04 '15 at 05:16
  • Your adding `Expenses` objects to your database. You have not shown the model for `Expenses` but I assume it has an ID property which is a `Guid`, so therefore inside the inner loop, you need `i.ExpenseId = Guid.NewGuid();` (and its `@` not `#` to notify a user) –  Dec 04 '15 at 05:29
  • @StephenMuecke: thank u so much , I cleared My Error ,Data Saved Successfully, It almost took 3weeks ,with in 3 mints u cleared this thank u so much – Felish Anand Dec 04 '15 at 05:39
  • yes , u right ,i am asked so many developers, no one can shortout this issue, but u did, once again thank u so much – Felish Anand Dec 04 '15 at 05:42

1 Answers1

1

You're generating a new Guid for the MaintenanceId property of ObjMaintenance, but you're not creating the Guid for the ID property of each Expenses objuect that you're adding. Assuming that property is named ExpenseId, then you loop needs to be

....
maintenance ObjMaintenance = new maintenance 
{ 
    MaintenanceId = Guid.NewGuid(),
    ....
};                   
foreach (var i in TVM.Expenses)
{
    i.ExpenseId = Guid.NewGuid(); // add this
    ObjMaintenance.Expenses.Add(i);
}
db.maintenances.Add(ObjMaintenance);
db.SaveChanges();

Side note: I suggest you look at the answers here, here and here for dynamically adding new items to a collection which allows you to add, edit and delete on the fly in 1/10 of the code you currently have.

Community
  • 1
  • 1