2

I insert a lot of records into an Entity Framework database and don't need them any more after I run .SaveChanges();. Moreover, I actually would like the memory to be released as soon as possible (for new records to be created). I don't keep any variables linking to old records objects but the GC doesn't seem to delete them, so, I think, it is the data context or something else who keeps them alive. How do I dispose them correctly to let GC to free memory they occupy?

maximpa
  • 1,958
  • 13
  • 16
Ivan
  • 63,011
  • 101
  • 250
  • 382

3 Answers3

3
  1. This isn't really a problem. Let the GC do its work.

  2. I think, it is the data context or something else who keeps them alive.

Correct. The basic solution is to Dispose the Context as soon and as often as possible.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Well, but I am going to use it again right after. I have to insert millions of records sequentially, do you mean I have to dispose and re-create the database connection that many times? Can't the context be forced to forget about the records inserted? – Ivan Nov 22 '12 at 09:54
  • 1
    Disposing a Context is not the same as closing the connection. – H H Nov 22 '12 at 10:04
0

Have you tried creating the context in a 'using' statement?

using(var context = new MyContext())
{
    // Do work here .....
}
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
0

SaveChanges() does not release the resources, it just commits the changes to the database.

To release the resources you need to call Dispose() method of the object context. It can be done explicitly by calling .Dispose() method or by putting your code inside the using statement:

using(var ctx = new EntityModel())
{
    // do the inserts
    ctx.SaveChanges();
}

Also, ObjectContext.Dispose() method closes the connection if it was opened by the Entity Framework, otherwise you can run out of the connections...

Here is a similar question: Should Entity Framework Context be Put into Using Statement?

Community
  • 1
  • 1
maximpa
  • 1,958
  • 13
  • 16