Entity Framework disposing with async controllers in Web api/MVC

后端 未结 2 1712
谎友^
谎友^ 2021-01-04 16:23

I have this little sample of code:

public class ValueController : ApiController
{
    private EstateContext _db;

    public ValueController()
    {
                 


        
2条回答
  •  自闭症患者
    2021-01-04 17:19

    You need to create a new instance of your EstateContext inside the async method.

    [HttpPost]
    public async void DoStuff(string id)
    {
        EstateContext db = new EstateContext();
        var entity = await db.Estates.FindAsync(id);
        db.SaveChanges();
    }
    

    However, I believe that if you change the return type of your controller action to Task then you should be able to reuse the context that is a member of the controller.

    [HttpPost]
    public async Task DoStuff(string id)
    {
        var entity = await _db.Estates.FindAsync(id);
        _db.SaveChanges();
    }
    

提交回复
热议问题