I found the reason for the error. The Entity Framework implicitly (re)opens the database connection by default before sending a query or saving the data. It closes the connection directly after querying and saving. SQLite or the provider seems to have problems with reopened connections. If the connection is closed and reopened, the connection is not able to access the locked database file (which is locked because of the transaction). This may be caused by the fact that ADO.NET connections are taken from a connection pool.
Anyway, the workaround is to open the connection explicitly before the TransactionScope and close it directly after:
bool connectionWasOpened = false;
try
{
// Open the connection explicitly if it was not yet opened (in the event that the transaction is executed within another transaction)
if (objectContext.Connection.State != System.Data.ConnectionState.Open)
{
connectionWasOpened = true;
objectContext.Connection.Open();
}
using (TransactionScope transactionScope = new TransactionScope())
{
...
transactionScope.Complete();
}
}
finally
{
if (connectionWasOpened )
{
objectContext.Connection.Close();
}
}
This gets the EF to not open/close the connection implicitly.
I'm not sure if this workaround works in all cases. In complex situations (involving sub transactions) the connection problem may still occur.