I get some data from a source and I want to add them in the database, so I open a context for each batch and use a transaction to commit the changes after all the data was added.
My code:
using (var conn = new SqlConnection(dataAccessSettings.DatabaseConnectString))
{
conn.Open();
using (var sqlTxn = conn.BeginTransaction(System.Data.IsolationLevel.Snapshot))
{
foreach (var dataBatch in GetData())
{
using (var context = new DataContext(conn, false))
{
context.Database.UseTransaction(sqlTxn);
context.DataTable.AddRange(dataBatch);
context.SaveChanges();
}
}
sqlTxn.Commit();
}
}
However, when the second context calls the context.Database.UseTransaction(sqlTxn)
I get the following error:
The transaction passed in must have a non-null connection. A null connection indicates the transaction has already been completed.
I set the contextOwnsConnection
constructor parameter of the context to false
so what exactly is closing my connection?