Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop a database using entity framework

I'm trying to remove a database form my application using entity framework. The code I use is the following:

using (var dbContext = container.Resolve<ApplicationDbContext>())
    {
      dbContext.Database.Delete();
    }

According to msdn this should work but nothing happens.

the dbContext is registered using ContainerControlledLifetimeManager and should be the same instance used to create the DB.

like image 493
memory of a dream Avatar asked Sep 29 '22 07:09

memory of a dream


2 Answers

Adding, updating and deleting instances of entity types needs dbContext.SaveChanges() to reflect changes.

However dbContext.Database.Delete() does not need dbContext.SaveChanges().

If you open connection for example from Sql Management Studio to your database and try to dbContext.Database.Delete() then you receive Cannot drop database "dbContext" because it is currently in use. If you restart you sql server, you drop those connections and then retry dbContext.Database.Delete() you successfully drop database.

Last thing is refresh database list in Sql Management Studio in order to see that database is not there any more.

Testing with this code snippet:

using (var dbContext = new dbContext())
{
    dbContext.Database.Delete();
}
like image 113
asdf_enel_hak Avatar answered Oct 03 '22 01:10

asdf_enel_hak


After @moguzalp and this (MSDN Database.Delete Function), I came with a solution for my case:

using System.Data.Entity;

Database.Delete("connectionStringOrName");

In my case I was trying to Recreate a mssqllocalDb database for test purposes. But whenever I used the same DbContext (or an immediately new one, disposing the first and opening another), it looked like the database was still up when I tried to create it.

Bad Example: (x)

public static void RecreateDatabase(string schemaScript)
{   
    using (DbContext context = new DbContext("connectionStringName"))
    {
        context.Database.Delete(); // Delete returns true, but...
        Database database = context.Database;
        database.Create(); // Database already exists!
        database.ExecuteSqlCommand(schemaScript);
    }
}

Working example: (/)

public static void RecreateDatabase(string schemaScript)
{   
    Database.Delete(); // Opens and disposes its own connection

    using (DbContext context = new DbContext("connectionStringName")) // New connection
    {
        Database database = context.Database;
        database.Create(); // Works!
        database.ExecuteSqlCommand(schemaScript);
    }
}

Context: I'm using this on an [AssemblyInitialize] function to test my ModelContexts

like image 42
Bruno Oliveira Avatar answered Oct 03 '22 03:10

Bruno Oliveira