Question: I create a copy of an mdf file with a random name. I inject that name into the connect string used by an EF6 DbContext. It opens fine, I run queries, etc, then I dispose of the context.
At this point if I attempt to delete the temp mdf file from the file system I cannot delete it; I get a "file is in use by another process" error.
Does anyone know if it's possible to force the connection to drop the lock on the mdf file when the connection closes? Or when the SqlExpress engines releases a localdb file lock?
I've tried using this:
master.ExecuteCommand(@"ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", db);
master.ExecuteCommand(@"exec sp_detach_db '{0}'", db);
... from this: How to detach a LocalDB (SQL Server Express) file in code ...but it doesn't work for me as I need to have this:
MultipleActiveResultSets=True
in my connection string, and so the ALTER DATABASE cannot be issued through a connection where MultipleActiveResultSets is on.
Thanks, Chris
Background (since I know someone will ask):
I've created a framework for our integration tests where each test gets a copy of the localdb. This works great and all the tests can run in parallel - especially if the temp folder for all the DBs is a RAMDisk folder, it's super fast. Unfortunately, I'm pushing the space-limits on the RAMDisk, if I clean up all the dbs after ALL the tests run (or before the start of the next test), so I want each DB to be deleted after each test completes. It looks like as long as the test engine / sqlexpress engine is running, the files remain locked. When it ends, the lock is lifted.