Database unable to be recreated after delete with Entity Framework

Nice little gotcha when getting started with Entity Framework using the built-in ASP.NET MVC templates. Wanting to start from a fresh database using the MSSQLLocalDB there is a few little things to do that aren’t necessarily obvious:

1. Delete the mdb and ldf

Go to the App_Data directory and delete.

If the delete fails, make sure you stop IIS Express which is holding a handle to the files.
Stop IIS Express

If the delete still fails, make sure you have closed connections in the server explorer in Visual Studio.
Close Server Explorer Connection

Still failing to delete? Go to Task Manager and kill the SQL Server Windows NT [sqlservr.exe] process.
Kill the process

2. Run Update-Database from the Package Manager Console

Update-Database

Fails with “The EntityFramework package is not installed on project ‘####’.
Check the default project is set to the correct one which contains the Migrations folder. Mine keep defaulting back to the Tests project.

Fails with “Cannot attach the file *.mdf as database”.
I found the answer on StackOverflow. The default connections string contains the Initial Catalog property. Which is all good for a full SQL Database but not LocalDb. Removing that property and it is all good.

Summary

Entity Framework seems quite good with Code First Migrations. I find the documentation really hard to get up to speed if you are coming new to it. Much of the documentation seems to focus around the difference and pieces together what to use for the latest version wasn’t the simplest. There is a bunch of little things you need to be aware of and practice with Add-Migrations and making sure everything is upgradable properly. Persisting with it [pun intended] has been worthwhile so far…