Search code examples
entity-frameworkef-code-firstcode-firstlocaldb

Delete localdb in Entity Framework Code First


I am writing some UnitTests with NUnit and Entity Framework. How to delete the whole localdb database from Entity Framework level?

Note: I don't want to clear the tables' data. I want to delete the whole database.

Also I am able to create a localdb file in my application working directory provided the database had not been created:

string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "");
var testDbFileName = String.Format(@"UnitTestDB.mdf");
var testDbFileNameWithPath = path + @"\" + testDbFileName;

var connectionString =
String.Format(
    @"Data Source=(localdb)\V11.0;Initial Catalog={0};Integrated Security=True;AttachDBFilename={1};MultipleActiveResultSets=True",
    "UnitTestDB", testDbFileNameWithPath);

//Here would be the code passing connection string to DbContext and so on..

Deleting only the file "UnitTestDB.mdf" is not enough. There is still a reference to the db in SQL Management Studio


Solution

  • There are 2 ways to do this in code. Stick to EF code first if you can :-)

    1) EF has a nice option on the context.

     Context.Database.Delete()
    

    2) if you want old school SQLCommand/SqlConnection approach something like this hack routine...

     public  bool DropDB(string DBName, string ConnectionString)
        {
    
            SqlConnection conn = null;
            SqlCommand cmd = null;
            string stmt = null;
    
            int rowCount = 0;
    
            if (string.IsNullOrEmpty(DBName))
                throw new ArgumentNullException(DBName, "DBName required");
    
            try
            {
                conn = new SqlConnection(ConnectionString);
    
               stmt = "DROP DATABASE " + DBName ;
    
                cmd = new SqlCommand(stmt, conn);
                conn.Open();
                rowCount = cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception)
            {
                //todo  whatever
                throw;
            }
            finally
            {
                if (conn != null) conn.Dispose();
                if (cmd != null) conn.Dispose();
            }
            if (rowCount == -1) return true;
            return false;
        }