entity .ToList() generates a System.OutOfMemoryException

后端 未结 3 2008
忘了有多久
忘了有多久 2021-01-21 10:03

I have a table with half a million rows. I need to update every single row but the ToList() fails:

List allContacts = objDatabase.Contacts.ToList         


        
相关标签:
3条回答
  • 2021-01-21 10:26

    try

    foreach (Contacts c in objDatabase.Contacts) c.value = newvalue;
    
    0 讨论(0)
  • 2021-01-21 10:29

    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.

    0 讨论(0)
  • 2021-01-21 10:41

    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.

    0 讨论(0)
提交回复
热议问题