开发者

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
                }

Fo开发者_JS百科r 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?


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.


Well, the error speaks for itself. After any of your **using** (IUnitOfWork uow = UnitOfWork.Current) your "global" context is disposed. So any attempt to access it will result in error.


I guess ObjectContext was disposed before you reached your using statement. Your linked question shows that you store context in HttpContext.Items or HashTable. If you wrapped all calls to UnitOfWork.Current by using only first block will work - all other will get disposed context from HttpContext or HashTable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜