Reputation: 2391
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.
Upvotes: 3
Views: 3451
Reputation: 2391
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;
}
}
Upvotes: 2
Reputation: 395
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...
Upvotes: 1