I have a problem with encapsulated try/catch blocks in combination with DbContexts from EF.
my code is seen in the following:
var hasToBeRepaired = false;
Exception ex = null;
try
{
SqlCeToSqLite(testContext);
}
catch(Exception exc)
{
hasToBeRepaired = true;
ex = exc;
}
if (hasToBeRepaired)
{
testContext.Dispose();
GC.Collect();
RepairComplete(_bl.BlShip.Imo, backupLastCe.BackUpPath);
}
In SqlCeToSqLite the following is used:
using(var emptydbcontext = new WriteObjectsContext(builder.ToString(), Providers.SqLite))
{
....
}
This is basically copying the tables from testcontext to a new context (emptydbcontext). When an exception is thrown, I want to restore from a previously made backup, which is done in the RepairComplete() function. This involves first deleting all items in the datapath, and then moving the ones from the backup there.
However, when I want to delete the database created by the emptydbcontext, it throws an IOException "The process cannot access the file '9622241.s3db' because it is being used by another process.".
This tells me the context is still open, though it should have been disposed when leaving the using() block with an exception? Collecting garbage for clearing any to be disposed objects didn't help. RepairComplete doesn't create any contexts, it just deletes the files (there it crashes) and then moves the backup'ed files.
Why doesn't it work like that, shouldn't the context be disposed when leaving the using block + going through GC? What can I do to fix this issue?