Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await Entity Framework ObjectContext disposed

I'm running into this issue where I get the following error:

A first chance exception of type 'System.ObjectDisposedException' occurred in EntityFramework.dll

Additional information: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I get that error while trying to access a table using EF 6. I have set the method to async and await the return value, but it still gives me disposed error.

 public async Task<List<Ticket>> GetAllOpenTwoTicketsAsync() {

        using (AssetTrackingEntitiesObj _edmObj = new AssetTrackingEntitiesObj()) {
            _edmObj.FullObjectContext.Connection.Open();
            return await _edmObj.Tickets
              .Where(t => t.TicketStatusType.isOpenTicket)
              .Include(t => t.AssetTickets)
              .Select(t => t).ToListAsync();
        }    

        
    }

here is the method that calls the tickets

 TicketsCollection = new ObservableCollection<Ticket>(await _ticketRepository.GetAllOpenTwoTicketsAsync());

Am I doing that correctly? Every method in my repository uses a using statement, creates its own objectcontext, opens its own connection and then does what ever it needs to, is this the correct manner for multiple async with EF6? Thanks in advance.

like image 326
user5660392 Avatar asked Feb 26 '26 13:02

user5660392


1 Answers

  1. _edmObj.FullObjectContext.Connection.Open(); isn't needed. The using statement takes care of opening and disposing the context. That's the main reason to use them over opening/closing/disposing resources yourself.

  2. .Select(t => t) is completely unnecessary. Just calling ToListAsync() will do the trick.

The rest of your code looks fine, so it's probably the first statement that is causing the error. Another cause could be that you try to access a navigation property that you didn't include, lazy loading doesn't work when your context is disposed.

like image 83
Alexander Derck Avatar answered Feb 28 '26 01:02

Alexander Derck