Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regenerate Code-First database without adding any data

In my code-first setup, I prefer not to allow the consumer (in this case a web-page) to be able to drop and recreate the database even at design time, for fear that I might forget to add appropriate logic later and shoot myself in the foot (to the effect of creating a database users with proper permissions before going live). Therefore this website has three projects associated with the solution:

  • Code First Project, which contains POCOs and initializers. There are two distinct ways of creating a DbContext instance, one that sets Database.SetInitializer to an initilizer that inherits from CreateDatabaseIfNotExists<MyContext> and the other way does with DropCreateDatabaseAlways<PanelisternaDbContext>. This ways I don't get any sneaky drop & recreates, and hopefully even if I somehow mess up the database user permissions later, the server side code wouldn't go mental and start deleting things.

  • Webpage Project, or generally any kind of consumer. The idea is that I create MyContext here which doesn't drop the database - ever.

  • Reset Project, which is a console app that actually does drop and recreate everything. It even asks me to type in some verification, so I don't run it by accident.

So, everything's great so far. Except I don't know how to actually drop and recreate the database without putting anything in it. I.e. the following code does what I want:

using (var myContext = MyDbContext.GetContext("connectionString", true)) 
//The trailing 'true' marks that the database is to be dropped and recreated.
{
    var user = new User {};
    myContext.Users.Add(user);
    myContext.SaveChanges();
    myContext.Users.Remove(user);
    myContext.SaveChanges();
}

As you can see, I'm adding and removing a User object so that SaveChanges() actually has something to do. If I just do a SaveChanges() the database would not drop/recreate.

So, without further ado, I'm looking for a cleaner method to achieve database recreation, and any comments or thoughts on this reset-based solution.

like image 816
Gleno Avatar asked Dec 21 '22 10:12

Gleno


2 Answers

In your console app, you could put the following:

Database.SetInitializer(new DropCreateDatabaseAlways<MyDbContext>());         
using (var myContext = MyDbContext.GetContext("connectionString")) 
{           
    context.Database.Initialize(force: true);      
} 

This should force a drop and recreate, and you could use a custom initializer to create some initial data if required.

like image 124
AlexWilson Avatar answered Jan 10 '23 08:01

AlexWilson


When you initialise you DBContext you can check that the database exists and create it if it doesn't.

public MyDbContext(){
    Database.CreateIfNotExists();
}
like image 23
Richard Forrest Avatar answered Jan 10 '23 06:01

Richard Forrest