gpt4 book ai didi

c# - 在 Entity Framework 中使用 DbContext 运行异步调用

转载 作者:行者123 更新时间:2023-11-30 20:23:24 31 4
gpt4 key购买 nike

我希望能够按如下方式运行异步调用:

[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. 方法时,会发生错误:

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.

使用的上下文在这里:

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;
}

}

上下文在 Controller 中作为类变量通过以下方式创建:

private MyContextInterface db = new MyContext();

我可以看到在方法结束时正在处理数据库上下文;但是,我需要在异步方法运行期间保留此上下文以访问所需的信息。我该怎么做?

最佳答案

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

关于c# - 在 Entity Framework 中使用 DbContext 运行异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973114/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com