Joe
Joe

Reputation: 4183

Moving WebSecurity.InitializeDatabaseConnection to Application_Start; cannot connect ---.mdf as database --- error

MVC4, EF5, code first, VS Express 2012, Win 7 Pro

When I move the

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

to the Application_Start of the Global.asax.cs (I've tried before and after the xxxConfig. files) I get the following error message.

Cannot attach the file 'D:\DevProj\MVC4Test\MVC4Tst\App_Data\aspnet-MVC4Test-20121123150620.mdf' as database 'aspnet-MVC4Test-20121123150620'

It runs fine from the InitializeSimpleMembershipAttribute and I deleted all LocalDB databases through SSMS. It is a new MVC4 internet project using all the defaults (installed VS 2012 Express two days ago). The only thing that has been edited is moving the WebSecurity.InitializeDatabaseConnection, excluding the InitializeSimpleMembershipAttribute from the project and commenting out references to it in the AccountController.

Any help appreciated.

Upvotes: 1

Views: 3080

Answers (1)

Joe
Joe

Reputation: 4183

The SimpleMembership DB has to exist before running

WebSecurity.InitializeDatabaseConnection("AccountDB", "UserProfile",
              "UserId", "UserName", autoCreateTables: true);

Once the SM DB has been created (say through migration) best practice in MVC4 is to wrap the call to WebSecurity in the Application_Start section of the Global.asax.cs.

 WebSecConfig.RegisterWebSec();

Place the WebSecConfig.cs file in the App_Start folder.

WebSecConfig.cs

using WebMatrix.WebData;

namespace MVC4Test
{
  public static class WebSecConfig
  {
    public static void RegisterWebSec() {
      WebSecurity.InitializeDatabaseConnection("AccountDB", "UserProfile",
              "UserId", "UserName", autoCreateTables: true);
    }
  }
}

Upvotes: 5

Related Questions