Search code examples
asynchronousopenapidbcontextasp.net-core-5.0

Can I call DBContext.SaveChangesAsync in my Web API and assume this task will continue while my method returns?


I have a basic Web API with a method like this:

[Route("/Add/{Data}", Name = "AddData")]
[HttpPost]
public void InsertData(DataObject Data)
{
    DataContext.DataTable.Add(DataObject);
    DataContext.SaveChangesAsync(); // <===== This!
}

Just want to be sure that this will work as expected as the SaveChangesAsync() task might still be executing while this method ends. Can I rely on this to work just fine, so my web service might respond slightly faster?


Solution

  • While it may be tempting, don't do it.

    The thread will still be held with one response sent, but any errors saving could cause app instability - you could be getting logs of failure that your clients don't see. If there are other operations that require that data, they would fail without ever "knowing why." Debugging would be a nightmare.

    Leave the transactions as transactions - and let the server give a true response for the operation you are performing.