1

I have a class level repository and inserting rows in some tables with populating their fields, I am doing this in a for-loop that has 10K items in it. So no where still I call SaveChanges(). I was thinking just call SaveChanges() one time at the end of for-loop and save them all at once. But looks like in the middle of my program it is Running out of memory and crashes. I have 16GB of RAM and resource monitor shows 42% is being used. So if I call SaveChanges() at the end of each item in the loop instead of at the end of the whole loop, does that make the size of it smaller and help with this memory issue?

  • Have you tried running the profiler to see if it does? My guess is that it won't clear memory since it caches results, but I could be wrong. – Nathan A Aug 08 '14 at 19:55
  • Some code showing the general flow would be nice. – Mike Aug 08 '14 at 20:00
  • Also - is your database running on your local machine, or something else? If it's running on your local machine, are you sure the DBMS isn't what's hogging all of the memory? 42% memory usage doesn't sound like enough to cause a crash, though. – Mike Aug 08 '14 at 20:09

2 Answers2

1

1)Do NOT call SaveChanges() at the end of each iteration ,it is too slow
2)Check this
When should I call SaveChanges() when creating 1000's of Entity Framework objects? (like during an import)
If you can use SqlBulkCopy ,it is very fast

Also check if your app is targeting x86 ,if it is you cannot access more than 2GB (actually it is less than that)

Community
  • 1
  • 1
George Vovos
  • 7,563
  • 2
  • 22
  • 45
  • I have put it on "AnyCPU" . So it is x86? – ConfusedSleepyDeveloper Aug 08 '14 at 20:29
  • 1
    Depends on your machine,more info here http://stackoverflow.com/questions/934314/maximum-memory-a-net-process-can-allocate and here http://stackoverflow.com/questions/14186256/net-out-of-memory-exception-used-1-3gb-but-have-16gb-installed – George Vovos Aug 08 '14 at 20:34
0

No that wouldn't save memory. I would suggest after each iteration, call SaveChanges(), set the object to null and create a new one for next iteration so:

foreach(kitten)
{
  myRepo = new Repo();
  //....creating records
  myRepo.SaveChanges()
  myRepo = null;
}
BobakDotA
  • 323
  • 1
  • 4