Dropping a Database Using Entity Structure

I am trying to drop my application's database form using entity framework. The code I'm using is the following:

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

      

According to msdn this should work, but nothing happens.

dbContext is registered with ContainerControlledLifetimeManager

and must be the same instance used to create the DB.

+3


source to share


2 answers


Adding, updating and removing instances of object types requires dbContext.SaveChanges()

changes to reflect.

However, it dbContext.Database.Delete()

does not need dbContext.SaveChanges()

.

If you open a connection, for example from Sql Management Studio, to your database and try to execute dbContext.Database.Delete()

, then you get Cannot drop database "dbContext" because it is currently in use.

. If you restart sql server you delete these connections and then try again dbContext.Database.Delete()

, you delete the database successfully.



The last thing is to update the list of the database in Sql Management Studio to see that this database is no longer there.

Testing with this piece of code:

using (var dbContext = new dbContext())
{
    dbContext.Database.Delete();
}

      

+2


source


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

using System.Data.Entity;

Database.Delete("connectionStringOrName");

      

In my case, I was trying to recreate the mssqllocalDb database for testing. But whenever I used the same DbContext (or a new one right away, getting rid of the first one and opening another), it looks like the database was still working 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 am using this in the [AssemblyInitialize] function to test my ModelContexts

+1


source







All Articles