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!