Manually drop and create DB in EF CodeFirst CTP5?

entity-framework

Question

For testing purposes I would like to manually be able to drop and recreate a DB using EF CodeFirst CTP5. How would I do this?

1
10
2/6/2011 9:37:14 AM

Accepted Answer

The DbDatabase class available as a property on your DbContext object offers a set of methods for directly working with database. You can use the Create and Delete method for this matter:

using (var context = new YourContext())
{
    context.Database.Delete();
    context.Database.Create();
    // Or
    context.Database.CreateIfNotExists();
}
21
2/6/2011 11:41:16 PM

Popular Answer

This works for me but not dave answer with entity framework 5.0. You will have to trigger a database trip that like a query in order to trigger the action.

Global.asax 
   Database.SetInitializer<MedicalVarianceDataContext >(new DataInitializer());

Elsewhere

 public class DropDatabaseInitializer<T> : IDatabaseInitializer<T> where T : DbContext, new()
    {
        public DropDatabaseInitializer(Action<T> seed = null)
        {

        }

    protected virtual void Seed(T context) { }
    public void InitializeDatabase(T context)
    {
        if (context.Database.Exists())
        {
            context.Database.ExecuteSqlCommand("ALTER DATABASE " + context.Database.Connection.Database + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
            context.Database.ExecuteSqlCommand("USE master DROP DATABASE " + context.Database.Connection.Database);
        }

        context.Database.Create();
        Seed(context);

    }
}

I guess you will also need to add context.savechanges();

    protected override void Seed(MedicalVarianceDataContext context)
    {

         new List<ViewLookUpIndividualUnit>{

            new ViewLookUpIndividualUnit{  MvrsIndividualUnit="Clinic" ,Active=true}


        }.ForEach(k => context.ViewLookUpIndividualUnits.Add(k));

        base.Seed(context);
        context.SaveChanges(); 
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow