title: How to overwrite .mdf file
body: <p>I am working on a project which involves using a database and I am unit testing it. Right now the tests create a database as a <code>.mdf</code> file and use it.</p>
  
  <p>What I want to do is to make a copy of this <code>.mdf</code> file somewhere else and before each test replace the original <code>.mdf</code> file with the copy I had just made. The problem is that when I try to do so, it says that the file is being used by another process. I found out that process is <code>sqlservr.exe</code>.</p>
  
  <p>My question is: is there any way to stop the server from using the file so I can replace it? I have tried the SQL Server BACKUP and RESTORE options, but they are not good enough for me because they slow down the process way too much.</p>
  
  <p>Any help would be much appreciated.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Ok, so a little more information on the problem. Basically I am working with improving performance of my unit tests. Most of the tests require a connection to a database, so I have a LocalDb in a <code>.mdf</code> file. This file is created during the <code>TestFixtureSetup</code>. Then, before each test (during the <code>SetUp</code>) the database is wiped via SQL commands. It seems to be not the most efficient way of recreating a fresh database for each test. So I have tried two different methods as of now:</p>
  
  <ol>
  <li>Use SQL BACKUP and RESTORE commands. This works, but it increases the execution time of my tests.</li>
  <li>Killing the <code>sqlservr.exe</code> process, locally copying the file and restarting <code>sqlservr.exe</code>. This also works, but increases the execution time as well.</li>
  </ol>
  
  <p>So basically I am looking for suggestions on how to improve the performance of recreating a completely empty database.</p>