Question:
I'm trying to insert data into the database, but I have an error when doing saveChanges();
after doing context.add()
several times, it has happened after 500, 2200 and 5500 times.
Mistake:
The transaction associated with the current connection has completed but has not been dropped. The transaction must be dropped before using the connection to execute 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 to 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 so it won't work? Thank you very much in advance!
Answer:
As said by comment, the correct way to solve it is using EntityFramework.BulkInsert , which has 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;
}