Sunday, June 2, 2013

Cannot Attach the File as Database...

Short post this time.

"Cannot attach the file as database....". I came across this error when rolling Membership into EF Code First. Searching, of course, led to Stack Overflow. Most of the answers were saying to drop and re-create the database. However this did not fit my situation as the database was not even created!

The solution was rather simple. Right click the App_Data folder and add a brand new (empty) database and run the solution again.

As a side note, it is quite common to get another error dealing with the database initialization. Your initialization code needs to run before the database is accessed. A good place to do that is in Application_Start in Global.asax.

protected void Application_Start()
{
   Web.Security.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}

Of course another place to put that line of code is in OnModelCreating of your DbContext class.