Get Next Id before being inserted to database MVC5

1545 views c#
5

Im trying to Get next ID before being inserted to database from Table RMA_History and i did as below in my Get Method and its working fine ,when i navigate to the page i can see Next ID , but in same page i also posting & Saving some data to database into RMA_History with Ajax , but i get this error

Cannot insert the value NULL into column 'Id',column does not allow nulls. INSERT fails.The statement has been terminated

*PS i just want to display next ID and not posting it.
Can anyone please help me or pointing me in the right direction what did i wrong!
Thanks in advance :)

Controller:
Get:

[HttpGet]
public ActionResult OpretRMA () {

    var autoId = data.RMA_History.OrderByDescending(c => c.Id).FirstOrDefault();

    CreateRMAVM model = new CreateRMAVM {
        AutoID = autoId.Id +1
};
    return View(model);
}

Post:

[HttpPost]
            public JsonResult ProcessCreateRMA(CreateRMAVM model)
            {
                var RMA = new RMA_History
                {
                   Kundenummer = model.Kundenummer
                };

                db.RMA_History.Add(RMA);
                db.SaveChanges();
                return Json(model, JsonRequestBehavior.AllowGet);
            }

View Model:

public class CreateRMAVM
    {
        public string Kundenummer { get; set; }
        public int AutoID { get; set; }
    }  

View:

        <div class="col-md-2">
           <div class="form-group">
             <label class="form-control-label">RMA ID</label>                                            
            @Html.TextBoxFor(model=>model.AutoID)
      </div>
        </div>
       <div class="col-md-2">
         <div class="form-group">
          <label class="form-control-label">Kundenummer</label>
            <input type="text" name="Kundenummer" id="Kundenummer">
            </div>
           </div>
  <button id="send" type="submit">Send</button>

JavaScript:

<script>

    $("#send").click(function (e) {

        e.preventDefault();

    var model = {
        Kundenummer: $("#Kundenummer").val(),
    }

    $.ajax({

          type: 'POST',
                    url: '@Url.Action("ProcessCreateRMA", "User")',
                    dataType: 'json',
                    data: {

                        Kundenummer: model.Kundenummer,
        },
        success: function (CreateRMA) {

            if (CreateRMA) {

                CreateRMA.Kundenummer = model.Kundenummer;
                console.log("Ok");
            }

            else {

                alert("What follows is blank: ");
            }

       },

        error: function ()
        {
            console.log('something went wrong - debug it!');
       }
        });
    });

</script> 

answered question

can you confirm if RMA_History table Id is auto incremental? and also can you confirm if you JS event is getting fired twice.

@Jawand yes id is auto incremental and i dont Think so

1 Answer

6

There are several problems here. The first is

var autoId = data.RMA_History.OrderByDescending(c => c.Id).FirstOrDefault();

CreateRMAVM model = new CreateRMAVM {
    AutoID = autoId.Id +1
  1. What happen if autoId comes back null? Granted this only happens on a new database but still..
  2. What happens if two users, Jack and Jill both try to use your website at the same time? Depending on the timing, both Jack and Jill might both think the next ID is the same number, like 23, for example Jack or Jill will fail, whoever goes second, when they create a new record in your table because you will have a duplicate ID.

You could use a GUID which would be globally unique as an ID. That way you could know what your next ID would be without worrying about the initial condition of your table, or about multiple users hitting your website at the same time. I usually just go with a different pattern. Instead of needing to know in advance what the ID is going to be, I have the controller method create the new row and return that ID to me if the store is successful.

posted this

Have an answer?

JD

Please login first before posting an answer.