Alex Rivera | Logout

Exception when code first tried to create database

Asked 2012-08-30T20:42:48.747
24

I've created a new ASP.NET MVC 4 application, and would like it to use code first. However it doesn't seem to initially create the database file if it doesn't exist already. If I delete the .mdf file from the App_Data folder, then I get the following exception when the app tries to access the database:

System.Data.SqlClient.SqlException: Cannot attach the file '<path-to-db-file>.mdf' as database '<my-db-file-name>'.

If I run it in the app in the debugger, then I can see that the exception is occurring in the InitializeSimpleMembershipAttribute::OnActionExecuting method when calling LazyInitializer.EnsureInitialized. The caught exception is:

[System.Reflection.TargetInvocationException]   {"Exception has been thrown by the target of an invocation."}   System.Reflection.TargetInvocationException

With an inner exception of:

[System.InvalidOperationException]  {"The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588"} System.InvalidOperationException

Which then has the first exception I mentioned above as the inner exception of that.

Any ideas what I'm doing wrong?

Update

I've just tried it with a brand new MVC4 app. I can replicate it by doing the following:

  1. Create the MVC app in the VS wizard.
  2. Run the app for the first time and go to the login page (note the mdf file now gets generated).
  3. Delete the mdf file, and go back to the login page. The exception is now thrown.
Edit
Report

1 Answer

1

You should never delete autocreated .mdf files in Explorer, only through the SQL Management tools or in the Object Explorer.

The issue you are getting (and can replicate in the steps you've provided) is that the database is still registered in LocalDb.

answered 2013-04-05T03:45:35.637

Your Answer