Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectContext instance has been disposed

I am using the entity framework the way described here: Entity framework uses a lot of memory

I realized I need to use "using" statement in order to work correct. When I am doing:

                using (IUnitOfWork uow = UnitOfWork.Current)
                {
                    CompanyRepository rep = new CompanyRepository();
                    m_AllAccounts = rep.GetQuery().
                        Select(x => new Account(x)).ToList(); ///HERE I GET THE EXCEPTION
                }

For this example, I getting:

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

What am I doing wrong?

like image 785
Naor Avatar asked Oct 12 '22 01:10

Naor


1 Answers

I may be wrong, however the first that comes to my mind is that probably UnitOfWork.Current returns an already-disposed unit of work.

Imagine the following code:

void MethodA ()
{
    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        // do some query here
    }
}

void MethodB ()
{
    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        // do another query here
    }
}

MethodA (); // works OK
// now UnitOfWork.Current is disposed
MethodB ();  // raises exception

The question comes down to what exactly UnitOfWork.Current does and what is is supposed to do. Should it create a new object each time it is accessed? Should it keep a reference unless it is disposed? This is not obvious and you might have been confused by this.

like image 66
Dan Abramov Avatar answered Oct 15 '22 11:10

Dan Abramov