Seyed Morteza Mousavi
Seyed Morteza Mousavi

Reputation: 6963

How to renew ObjectContext in Entity Framework?

I have some large query (insert and update) and for memory related issues I decided to reduce my heavy query to smaller batch of 1000 records insert and update query. My code is like this:

for(/*200 batch of 1000 insert queries*/)
{
    Add1000Records(objectContext);
    objectContext.Dispose();
    objectContext= null;
    objectContext= new MyObjectContext();
}

When first 1000 record inserted and objectContext renewed for inserting second 1000 record I face following error:

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

Upvotes: 0

Views: 466

Answers (2)

George Lica
George Lica

Reputation: 1816

Instead of managing context lifetime outside your insert method i would prefeer to manage it inside your Add1000records method. Make use also of the c# "using" statement wich would be translated into a try - finally block. In finally, dispose is guaranteed to be called even if an exception would be thrown. Also, maybe inside your function call you keep references somehow to objects that you save and later you use them / reattach them

Upvotes: 1

wiretext
wiretext

Reputation: 3342

By default Entity Framework uses lazy-loading for navigation properties.here problem with dispose method When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.

for(/*200 batch of 1000 insert queries*/)
{
    Add1000Records(objectContext);
}

Upvotes: 0

Related Questions