3

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.

0

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

1 Comment

The Selects weren't needed, thanks. I did end up having to use some of EF transactions and turned off lazy loading completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.