In an ASP.NET Webforms application on .NET 4.0 and a Web API, I attempt to add an order and orderRow to the database, but I get this error:
Error: new transactions are not allowed because there are other running threads in the session
From the client, I run an Ajax post to the controller, which has the following code for inserting a value into the database:
private readonly MyDatabaseEntities _ctx;
public ComponibileController()
{
_ctx = new MyDatabaseEntities(@"xxx");
}
[HttpPost]
public void Post([FromBody] ComponibileCreate model)
{
if (!ModelState.IsValid) return;
var taskWork = System.Threading.Tasks.Task.Run(() => SaveOnDatabase(model, utente));
...query
SendMailToUser(...);
taskWork.Wait();
}
public void SaveOnDatabase(ComponibileCreate model, string utente)
{
try
{
using (_ctx)
{
var ordine = new COM_ORDINI
{
..,
};
foreach (var item in model.Righe.ToList())
{
var righe = new COM_RIGHE
{
...
};
ordine.COM_RIGHE.Add(righe);
}
_ctx.COM_ORDINI.Add(ordine);
_ctx.SaveChanges();
}
}
catch (Exception e)
{
}
}