Search code examples
c#entity-framework-coreasp.net-core-3.1ef-core-3.1

CreateAsync very slow on DbContent


I am using EF for .NET Core 3.1

I have a DbContext which is taking ages to save 3000 objects

This seems to get slower the further into the loop

Has anyone had this?

I have tried AddAsync and Add with no difference

foreach (var item in itemsToSave)
{
  await _myRepository.CreateNonThreadedAsync(item, false);
}

In my repository....

public async Task CreateAsync(TEntity entity, bool isSaved = true)
{
  await DbContext.Set<TEntity>().AddAsync(entity);
  if (isSaved)
  {
      await SaveChangesAsync();
  }
}

    
public async Task CreateNonThreadedAsync(TEntity entity, bool isSaved = true)
{
    DbContext.Set<TEntity>().Add(entity);
    if (isSaved)
    {
        await SaveChangesAsync();
    }
}

I have to turn on change tracking because this is part of a process where I call SaveChangesAsync on the context once everything is finished

There is another piece of logic outside of this where I call SaveChangesAsync so that is why it is not here

I tried calling AddRangeAsync but nothing gets saved after SaveChangesAsync has been called and there are no errors

Paul


Solution

  • Try this code

    await DbContext.Set<TEntity>().AddRangeAsync(itemsToSave):
    await SaveChangesAsync();