【发布时间】:2015-05-12 10:41:29
【问题描述】:
我希望能够按如下方式运行异步调用:
[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.
}
但是,当异步方法命中db. 方法时,会发生错误:
EntityFramework.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
附加信息:操作无法完成,因为 DbContext 已被释放。
使用的上下文在这里:
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;
}
}
上下文在控制器中作为类变量通过以下方式创建:
private MyContextInterface db = new MyContext();
我可以看到,随着方法的结束,数据库上下文正在被释放;但是,我需要在异步方法期间保留此上下文以访问所需的信息。我该怎么做?
【问题讨论】:
-
如何创建/处置 DbContext?
-
@SLaks 这是一个通过EntityFramework的数据库连接。
-
DbContext实例是如何创建/处置的? -
@SLaks 我已经添加了如何在控制器和上下文类中创建上下文。上下文通过 EntityFramework 连接到数据库。
标签: c# .net entity-framework asp.net-web-api dbcontext