I load an object/entity from the database:
var db = new DbContext();
//...
var item = db.Items.First();
Then I want to perform two asynchronous tasks, that when returned, update data on the item:
var task1 = Function1(db, item);
var task2 = Function2(db, item);
await Task.WhenAll(new Task[] { task1 , task2 });
The two functions will have some code that gets, sets & saves a (different) property on the item, like so:
var orderId = await CallApi();
item.OrderId = orderId;
db.Entry(item).State = EntityState.Modified;
await db.SaveChangesAsync();
However, as they are running asynchonously, I'm getting the error: A second operation started on this context before a previous asynchronous operation completed.
I tried newing up a dbContext in the Functions, but then I get the error An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
I understand why I'm getting both of these errors, my question is: what coding pattern would best resolve this?
EDIT Ok, so the above was a simplified example. In reality, there is a lot more work that goes on in the functions, so it would be difficult to move all that logic out of the function and into the calling method. I also want that all that work to be self-contained.
The properties on the item that Function1 and Function2 update are discrete. I'm using this library to ensure that the save doesn't overwrite all the fields.