In MVC4, WebSecurity.InitializeDatabaseConnection causes Cannot open database requested by the login

457 views Asked by At

I'm trying to create a simple login using simple membership, I noticed that when database is already created I am able to run the application with no errors, however when I try to run the application without an existing database I'm getting this error => Cannot open database "OdeToFoodDb" requested by the login. The login failed. Login failed for user 'mycomp-PC\mycomp'

Cannot open database requested by the login. The login failed.

Is there a solution wherein even if I don't create the database manually it will be created by automatically.

Here is my code:

Code for global.asax.cs

protected void Application_Start()
        {

            if (!WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection("OdeToFoodDb", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            }


            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }




 public class OdeToFoodDb : DbContext
    {
        public DbSet<Restaurant> Restaurants { get; set; }

        public DbSet<RestaurantReview> Reviews { get; set; }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

My database context is also the name of my database in my web.config

Sir/Ma'am your answers would be of great help. Thank you++

1

There are 1 answers

0
joelmdev On

It's likely that you aren't restarting your application. App_Start runs only once and that's the only time the database and tables are initialized, so if your database is deleted and the app is not restarted, you will obviously receive errors as you'd be attempting to connect to a non existent database. Restarting the application in IIS should clear this up.