How to improve the performance of a foreach

3

I'm consuming a webservice , which has at least 5557 records.

The problem is after consuming. I have to add the records in my database, and for that, I have to make a foreach , which ends up hindering the performance a little, taking an average of 5 minutes.

How do I get better?

var tb_municipio_ws = _ServiceReaderClient.MunicipioListar();

if (tb_municipio_ws.Items != null || tb_municipio_ws.Item != null)
{
    foreach (var item in tb_municipio_ws.Items)
    {
        var tbMunicipios = new TB_MUNICIPIOS
        {
            MUN_ID = item.MunId,
            /*
            ....
            */
        };
        _context.TB_MUNICIPIOS.Add(tbMunicipios);
    }
}
_context.SaveChanges();
    
asked by anonymous 22.12.2014 / 17:09

1 answer

1

Probably the cause of the slowness is not just the call to the webservice, because even with the locally available data the Entity Framework would continue to check changes (DetectChanges) for each included record. The more records, the slower that check becomes.

Try turning off AutoDetectChanges by setting the AutoDetectChangesEnabled attribute to false , like this:

_context.Configuration.AutoDetectChangesEnabled = false;

if (tb_municipio_ws.Items != null || tb_municipio_ws.Item != null)
{
    foreach (var item in tb_municipio_ws.Items)
    {
        var tbMunicipios = new TB_MUNICIPIOS
        {
            MUN_ID = item.MunId,
            /*
            ....
            */
        };
        _context.TB_MUNICIPIOS.Add(tbMunicipios);
    }
}
_context.SaveChanges();

_context.Configuration.AutoDetectChangesEnabled = true;
    
22.12.2014 / 17:19