I want to be able to run an asynchronous call as follows:
[Route("doit"),ResponseType(typeof(MyModel))]
public IHttpResponse PostAsyncCall(MyModel model){
//Code removed for simplicity
Task.Factory.StartNew(() => asyncStuff(model.id);
return OK(model);
}
private void asyncStuff(int id) {
MyModel model = db.MyModels.find(id);
//Do things here. Long call to other webservices/processing of data. Time intensive normally.
User user = db.Users.find(model.userId);
//Do more things. Time intensive normally.
}
However, when the async method hits the db.
methods an error occurs:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The operation cannot be completed because the DbContext has been disposed.
The context used is here:
public class MyContext : DbContext, MyContextInterface
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
public MyContext() : base("name=MyContext")
{
}
public System.Data.Entity.DbSet<MyAPI.Models.User> Users { get; set; }
public System.Data.Entity.DbSet<MyAPI.Models.Request> Requests { get; set; }
public void MarkAsModified(Object item)
{
Entry(item).State = EntityState.Modified;
}
}
The context is created in the controller as a class variable via:
private MyContextInterface db = new MyContext();
I can see that the db context is being disposed of as the method ends; however, I need to retain this context for the duration of the asynchronous method to access the information needed. How can I do this?