3

How can EF5/CodeFirst be used to re-create a LocalDb database if it is deleted from the file system?

All of the articles I have found discuss enabling migrations or running update-database. Which only pertain to design time.

I'm looking for a solution that can be used at runtime.

I'm using DropCreateDatabaseIfModelChanges as a custom initializer and this works great during development and when the database is first created at runtime. However, the database is never created a second time, for example; if a user deletes the LocalDb database from the file system.

I've tried manually creating the database and, although the files get created successfully, the schema is never generated (error is "Model compatibility cannot be checked because the database does not contain model metadata.").

Thanks, in advance.

2 Answers 2

2

Figured it out... actually pretty logical / easy when you think about it.

LocalDb hangs onto the catalog name after the database has been created. And, in this app, since the name of the catalog is static, LocalDb understands that the database has already been initialized. Formally detaching the database (even though it is not on the file system) will cause LocalDb to treat it as a new catalog during the next call.

Here's the detach code. I'd recommend calling this from within an accessor only after checking to ensure the file really IS missing...

    public static bool DetachDatabase(string dbName)
    {
        try
        {
            string connectionString = String.Format(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True");
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = String.Format("exec sp_detach_db '{0}'", dbName);
                cmd.ExecuteNonQuery();

                return true;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return false;
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this EF 5, Code First - Create a new database and run all migrations programatically

Alternatively I would check if the database file exists then if the file was deleted then I would connect to master database and execute delete command and then try to create the context...

1 Comment

Hahaha... thanks, shinnra. I was so busy being anal while posting an answer that I never hit "refresh" to see if anyone responded. Thanks for the link... definitely gonna try that method as well. :)

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.