Entity Framework and Web API ObjectDisposedException

后端 未结 3 1853
予麋鹿
予麋鹿 2021-01-14 18:15

I have a data layer that uses Entity Framework 5 to connects to Sql Server. I also have a LINQ query that gets some data. This query fails when used with Web API. I get the

相关标签:
3条回答
  • 2021-01-14 18:26

    This is an issue with lazy loading. The more appropriate way to do this is to not dispose the DbContext till the request is done processing. You can do it in a couple of ways,

    1) dispose it in the controller. framework ties the controller's life time with the requests life time.

    public class MyController : ApiController
    {
        private SaleManager _saleManager = new SaleManager();
    
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                _saleManager.Dispose();
            }
        }
    }
    

    2) explicitly tie the resource with the request, (useful in cases where you are not inside a controller) using Request.RegisterForDispose()

    SaleManager saleManager = new SaleManager();
    Request.RegisterForDispose(saleManager);
    
    0 讨论(0)
  • 2021-01-14 18:38

    This happens because lazy loading is being performed after your DbContext has been disposed.

    To resolve the issue you can disable lazy loading by doing this:

    container.Configuration.LazyLoadingEnabled = false;
    
    0 讨论(0)
  • 2021-01-14 18:38

    There must be an issue with lazy loading and the include not working as expected - try changing your code to select the actual object and the included entities.

    using (MyContext container = new myContext())
    {
        var result = container
            .Sales
            .Include("Products")
            .Where(s => s.Id == id)
            .FirstOrDefault();
        result.Products.ToList();
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题