gopi ram

gopi ram

  • NA
  • 13
  • 1.6k

Transactions In .net core Web API Controller

Sep 24 2018 2:04 AM
Hi... I am very new to .net core framework and I have implemented code as bellow

public 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 table
inv.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 class

public 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 back
only main method changes are rolling back

if Qty is negative then also the changes has to be rolled back
If db.saveChanges() not included in inner method then the inner method data is not saving to the database.
Please advice If code is wrong 

Answers (1)