0

Is it possible to drop the application's database if the application is reinstalled?

EDIT: The client wants the database to be "purged" every time a new version of the application is installed. DropCreateDatabaseIfModelChanges won't cut it because they might install/reinstall the application without changes in the model.

8
  • 1
    can you made this quesion more specific, and describe what you need ? Commented Apr 19, 2016 at 10:39
  • 1
    What do you mean by reinstall ? if the model has changed ? Commented Apr 19, 2016 at 10:40
  • 1
    Need some more insight. Why do you want to drop the db ? you will lose previous data. Think about an app upgrade. It would be too costly to drop the db right ;) Commented Apr 19, 2016 at 10:40
  • Don´t drop data in a working envireonment, even if the data-model changes. YOu should create some migration-software to migrate existing data from one model to the newer one. Commented Apr 19, 2016 at 10:41
  • 1
    Possible duplicate of How to recreate database in EF if my model changes? Commented Apr 19, 2016 at 10:42

2 Answers 2

1

If you use some setup program (MSI, for example) you need add custom actions on Update, Unistall or Re-install events that deletes the database.

Other solution is to add it to the main code:

if (IsVersionChanged()) {

    if (Database.Exists(...)) { Database.Drop(...); }
} 

But it does not address the Re-Install case (you may try to detect this case by analyzing a file timestamp that should be always overwritten on installation/re-installation but it is only worth doing if you don't have a setup program).

There're several ways how you can implement the IsVersionChanged. For example, you can keep the version in the database itself or keep the last version in the windows registry.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'll try your solution.
0

You can use Database SetInitializer static member with desired parameter. Sample for Create if there is no db.

public class YourDbContext : DbContext 
    {

        public YourDbContext (): base("yourConnectionString") 
        {
            Database.SetInitializer<YourDbContext>(new CreateDatabaseIfNotExists<YourDbContext>());
        }  
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.