【问题标题】:Running Async Calls with DbContext in Entity Framework在实体框架中使用 DbContext 运行异步调用
【发布时间】: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


【解决方案1】:

您开始了一项任务,但您没有等待它,因此您立即调用 OK。 到长时间运行的任务完成时,您的数据库上下文确实已被释放。 只需添加一个 await 即可解决您的问题。

【讨论】:

  • 我不希望该方法等到任务完成。我希望它在异步任务在后台运行时立即返回,以消除用户等待这个长时间运行的任务。
  • 那么你需要重新考虑你的设计。另一种选择是,您确实确保在需要时创建上下文,或者在您真正完成时而不是更早地释放上下文。根据到目前为止我在您的代码中看到的内容,我无法确切地知道在哪里做。
  • 我不确定该采取什么方向。哪些进一步的信息将有助于进一步澄清问题?
  • 如果您在查找之前不需要 dbcontext,请在确实需要时新建它并使用 using 子句。我用谷歌搜索了一下,但无法立即找到与您的问题类似的问题。
  • 我确实找到了这个链接:stackoverflow.com/questions/17577016/…
猜你喜欢
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多