entity .ToList() generates a System.OutOfMemoryException

元气小坏坏 提交于 2019-12-02 07:26:54

Here is a solution using chunking. It will dispose of the container (and the downloaded entities) after every chunk. Memory should be released by the GC long before your system runs out of memory.

int chunkSize = 50;
int curCount = 0;

while (true)
{
    using (var db = new DbEntities())
    {
        var chunk = db.Contacts.Skip(curCount).Take(chunkSize).ToArray();
        curCount += chunkSize;

        if (chunk.Length == 0) break;

        foreach (var contact in chunk)
        {
            //do any work for the contact here
            contact.Something = "SomethingNew";
        }

        db.SaveChanges();
    }
}

Feel free to play around with the chunk size. The larger the chunk, the faster the entire process should be, but it will use up more memory.

How about

IEnumerable<Contacts> allContacts = objDatabase.Contacts.AsEnumerable();

Never convert allContacts to a list. Just use is like an enumerator and apply Foreach loop to access each contacts.

try

foreach (Contacts c in objDatabase.Contacts) c.value = newvalue;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!