Error entering data into bank, EF 6

5

I'm trying to insert data into the database, but I have an error doing saveChanges(); after doing context.add() several times, it's happened after 500, 2200, and 5500 times.

Error:

The transaction associated with the current connection has completed, but has not been discarded. The transaction must be discarded before using the connection to execute the SQL statements.

I have a function that inserts the data:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 30, 0)))
{
    Contexto context = null;
    try
    {
        context = new Contexto();
        context.Configuration.AutoDetectChangesEnabled = false;

        int count = 0;            
        for (int i = 0; i < textoLido.count; i++)
        {
            //criando instancia da entidade 
            // adicionando os dados nela;

            ++count;
            context = AddToContext(context, entidade, count, 100, true);
        }

        context.SaveChanges();
    }
    finally
    {
        if (context != null)
        context.Dispose();
    }

    scope.Complete();
    }

And a function that recreates the context after so many additions in the context:

private Contexto AddToContext<Entity>(Contexto context,
Entity entity, int count, int commitCount, bool recreateContext) where Entity : class
{
    context.Set<Entity>().Add(entity);

    if (count % commitCount == 0)
    {
        //erro acontece aqui
        context.SaveChanges();

        if (recreateContext)
        {
            context.Dispose();
            context = new Contexto();
            context.Configuration.AutoDetectChangesEnabled = false;
        }
    }

   return context;
}

How can I make this insert work or will it not work? Thank you!

    
asked by anonymous 16.10.2015 / 22:00

1 answer

2

As stated by comment, the correct way to solve this is by using EntityFramework.BulkInsert , which has your NuGet package .

An example usage would be:

using EntityFramework.BulkInsert.Extensions;

private Contexto AddToContext<Entity>(Contexto context, Entity entity, int count, int commitCount) where Entity : class
{
    context.Set<Entity>().BulkInsert(entity);

    if (count % commitCount == 0)
    {
        //erro acontece aqui
        context.SaveChanges();

        // Isto não precisa
        // if (recreateContext)
        // {
        //    context.Dispose();
        //    context = new Contexto();
        //    context.Configuration.AutoDetectChangesEnabled = false;
        // }
    }

   return context;
}
    
22.08.2016 / 16:28