System.OutOfMemoryException using Entity Framework?

后端 未结 2 474
再見小時候
再見小時候 2021-01-05 00:09

I am trying to save hundreds of thousands of records using Entity framework. After saving few hundreds of thousands of records I get following error:

:System.OutOfMe

2条回答
  •  时光说笑
    2021-01-05 01:07

    How many objects are you going to save and how big is single object? DbContext holds references to all objects you added with AddObject call. Calling SaveChanges does not purge its internal data structures so if you call your code for 1M objects you will have 1M object in memory and they will be fully alive because their root object for GC will be the context instance which is still in scope of your running code.

    If you want to avoid the memory issue you should use a new context instance for every 1000 records (or even every record). The only difference between running SaveChanges for 1000 records and for single record is the automatically involved transaction.

提交回复
热议问题