0

I am using EF6 in a project. Because of the speed limitations for adding many (i.e. 10,000+) entities via EF6 I have resorted to doing the database additions outside of EF6. The code that does the database 'Add' returns a list of entity objects that represent the new database rows.

I then want to attach these new entities to my repository so that the Database and the repository are in sync. To do this I am using the following method:

public void AttachRangeNoTracking<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
    {

        try
        {
            _context.Configuration.AutoDetectChangesEnabled = false;

            foreach (var entity in entities)
            {
                _context.Set<TEntity>().Attach(entity);
            }
        }
        finally
        {
            _context.Configuration.AutoDetectChangesEnabled = true;
        }
    }

The problem is that this code is quite time consuming when it is passed many entity objects. In tests 5000 entities could take 18 secs which is way to long.

Are there any other performance improvements or alternative approaches that might be quicker for attaching large numbers of entities to the DbContext?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cleve
  • 1,273
  • 1
  • 13
  • 26
  • Rather than attaching them after inserting them all, are you able to just run a query to project them out into the object you need? This will probably be significantly quicker that 'attaching' all the entities like this. – Paddy Jul 09 '21 at 10:02
  • @Paddy, not quite sure I understand your comment `are you able to just run a query to project them out into the object you need?`. I will mention again, that after I run the bespoke code to add records to the database, it also returns as objects the 'entities' that have just been added to the database. It is these that I am then passing into the `AttachRangeNoTracking` method. – Cleve Jul 09 '21 at 10:43
  • I was assuming you wanted to attach them in order to query it? If not, then why attach them at all? – Paddy Jul 10 '21 at 11:40

0 Answers0