Make a backup before the database is dropped DropCreateDatabaseIfModelChanges

We use the ef code first with the semantic model DropCreateDatabaseIfModelChanges.

There isn't a lot of sensitive information in the database, so it's okay if it goes down.

However, we should be able to back up the old version before deleting it. Is it possible?


source to share

1 answer

We will implement the interface shortly IDatabaseInitializer<T>


So far we are using this code (which I know is not perfect):

Database.SetInitializer<OurdatabaseModel>(new OurdatabaseInitializer());
_instance = new OurdatabaseModel();

    // force model creation
catch (InvalidOperationException)
    if (_instance == null)

    // database exists. Let back it up.
    string dbPath = _instance.Database.Connection.Database.Replace("|DataDirectory|", Program.DataDirectory);
    File.Move(dbPath, dbPath + "." + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".sdf");

    // and now the CreateDatabaseIfNotExists<T> will take care of the rest
    _instance = new OurdatabaseModel();




All Articles