Transactions In .net core Web API ControllerGRgopi ram8yAsked Sep 24, 2018, 2:04 AM1.4kHi... I am very new to .net core framework and I have implemented code as bellowpublic async Task addItem([FromBody]ImsCoLines model){if (model == null){return BadRequest();}using (db){using (var _ctxTransaction = db.Database.BeginTransaction()){DateTime today = helper.getISTDate(); model.forEach(obj=>{db.ImsCoLine.Add(obj);db.SaveChanges(); ImsInvTxn inv = new ImsInvTxn();inv.CoLineID=obj.CoLineID; // getting only after creating the record in ImsCoLine tableinv.InvQty = obj.Qty;inv.BatchId = obj.BatchId;inv.CreatedBy = obj.CreatedBy;inv.CreatedDate = today;db.ImsInvTxn.Add(inv); var result=helper.updateInventory(obj);if(result!="OK") res=result;}); try{if (res == "OK"){await db.SaveChangesAsync();_ctxTransaction.Commit();}else{_ctxTransaction.Rollback();}}catch (Exception e){_ctxTransaction.Rollback();throw e;} return Ok();} updateInventory method in helper classpublic string updateInventory(ImsCoLine invObj){ string res="";var inv = db.ImsInvItem.FirstorDefault(y => y.ItemID== invObj.ItemID);if(inv != null){ inv.Qty=inv.Qty - invObj.Qty; if(inv.Qty<0) res="Negative Qty"; else res="OK";} if (res == "OK"){try{db.SaveChanges();}catch (Exception ex){throw ex;}}return res;} When an exception is raised in main method (await savechangesAsync()) the inner method changes are not rolled backonly main method changes are rolling backif Qty is negative then also the changes has to be rolled backIf db.saveChanges() not included in inner method then the inner method data is not saving to the database.Please advice If code is wrong
Laxmidhar Sahoo8y agoPosted Sep 29, 2018, 8:26 AMdb.Savechanges() is syn method that can not call in asyn method .So call await method
Laxmidhar SahooPosted Sep 29, 2018, 8:26 AM