Why does ASP.NET MVC 4 SimpleMembershipProvider keep creating aspnetdb.mdf?

c# Oct 11, 2013

When you create a new ASP.NET MVC 4 Internet Web Application it creates a nice template with authentication enabled with new SimpleMembershipProvider It contains InitializeSimpleMembershipAttribute class which creates built-in Entity Framework Code First database and initializes Simple Membership:

using (var context = new UsersContext()) 
{
    if (!context.Database.Exists())
    { 
        // Create the SimpleMembership database without Entity Framework migration schema       
        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
    }
}
WebSecurity.InitializeDatabaseConnection( "DefaultConnection", "UserProfile", "UserId", "UserName",  autoCreateTables: true);

There are two things you need to know. First, if you use your own Entity Framework DataContext, it's important to create the database before the membership initialization.

Otherwise WebSecurity.InitializeDatabaseConnection() will create the UserProfile table itself and Entity Framework will fail to initialize. This one might be a little obvious, but the second thing is more subtle. If you somehow use Membership functionality (like AuthorizeAttribute or Roles.IsUserInRole() before 'InitializeSimpleMembershipAttribute' is used it will create aspnetdb.mdf file in 'App_Data' folder. This is happening because initially the application is set up to use Membership (not Simple) and 'WebSecurity.InitializeDatabaseConnection()' will actually overwrite that to Simple Membership (and after that it will create the necessary tables).

Solution to this is to move the code above to 'Global.asax', into 'Application_Start' method. That way you can be sure that Simple Membership is initialized as early as possible.

Mohammad Mustakim Ali

I'm a Software Engineer living in London, UK. My passion is to make *very fast* software with great user experience and I have just got little better on this than I was yesterday.