Cannot access a disposed object. A common cause of this error is disposing a context

后端 未结 4 2381
梦谈多话
梦谈多话 2020-12-16 13:32

I have written a simple application and when I navigate to my edit page the below error pops up.

Microsoft.EntityFrameworkCore.Query[10100]

<
相关标签:
4条回答
  • 2020-12-16 13:46

    This is because of your method return type async void. In general, when you are using async void in your code it’s bad news, because:

    • You can’t wait for its completion
    • Any unhandled exceptions will terminate your process (ouch!)

    So return async Task instead of async void from your method as follows:

    public async Task OnGet(int id)
    {
        Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);
    
        if(Book == null)
        {
           RedirectToPage("Index");
        }
    }
    

    For more details:

    • C# – beware of async void in your code

    • Cannot access a disposed object in ASP.NET Core when injecting DbContext

    0 讨论(0)
  • 2020-12-16 13:47

    This is another anwser for who gonna read this topic.

    I tried to trigger asnyc method with javascript. Because of that it can't triggered and so result didn't calculated by async method. I was returning json object to view like this in dotnet core mvc.

    return Json(_service.AsyncMethod(parameter));
    

    My IActionResult is not async so I can't add "await". I just add ".Result" and it calculate result.

    return Json(_service.AsyncMethod(parameter).Result);
    
    0 讨论(0)
  • 2020-12-16 13:57

    What I am about to post is NOT the answer to this particular question. But it is related so just to save somebody headache I am posting it. I was encountering this same error

    System.ObjectDisposedException: Cannot access a disposed object. etc

    The following was the code with the bug (can you see it?):

    [HttpGet("processs/oxxo-spei/ticket-email/{paymentIdx}")]
    public StatusCodeResult ProcessOxxoSpeiTicketEmailAsync(string paymentIdx)
    {
        var paymentId = paymentIdx.DecodeRef();
                
        var response = _orderEngine.ProcessOxxoSpeiTicketEmailAsync(paymentId);
    
        return StatusCode(200);
    }

    The following change fixed it:

    [HttpGet("processs/oxxo-spei/ticket-email/{paymentIdx}")]
    public async Task<StatusCodeResult> ProcessOxxoSpeiTicketEmailAsync(string paymentIdx)
    {
        var paymentId = paymentIdx.DecodeRef();
                
        var response = await _orderEngine.ProcessOxxoSpeiTicketEmailAsync(paymentId);
                    // ^^^^I HAD FORGOTTEN TO PUT AWAIT
        return StatusCode(200);
    }

    Yes that's right I had forgotten to put "await" before a function that used an EF Core dbcontext. Adding 'await' fixed it. So easy to miss it, especially if you're tired and under deadline.

    0 讨论(0)
  • 2020-12-16 14:09

    Here is what actually worked for me in a situation where I was getting the same error as above when trying to access the data in Startup.cs to run some startup data building functions on server load, rather than a specific Controller action:

            IServiceScope scope = provider.CreateScope();
            YourDbContext context = scope.ServiceProvider.GetRequiredService<YourDbContext>();
    

    In the Configure method of Startup.cs, with IServiceProvider included as a parameter:

    public async void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider provider)
    

    Just including that for anyone who wants to do the same in Startup.cs.

    0 讨论(0)
提交回复
热议问题