Search code examples
asp.net-mvc-4simplemembership

You must call “WebSecurity.InitializeDatabaseConnection” exception when I already have


So I'm trying to seed my database with the following initializer

public class DbInitializer : DropCreateDatabaseAlways<IAMContext>
{
    protected override void Seed(IAMContext context)
    {

        WebSecurity.InitializeDatabaseConnection("IAMContext",
          "UserProfile", "UserId", "UserName", autoCreateTables: true);
        var roles = Roles.Provider;
        var membership = Membership.Provider;

        if (!roles.RoleExists("Admin"))
        {
            roles.CreateRole("Admin");
        }
        if (!WebSecurity.UserExists("test"))
        {
            WebSecurity.CreateUserAndAccount("test", "password");
        }

        if (!roles.GetRolesForUser("test").Contains("Admin"))
        {
            roles.AddUsersToRoles(new[] { "test" }, new[] { "admin" });
        }

        context.Products.Add(new Product
        {
            Id = 1,
            Name = "Homunculi",
            Price = 85,
            LongDescription = "Happens when failed human transmutations occur", 
            ShortDescription = "Failed Xmute", 
            media = "CD"
        });


        base.Seed(context);
    }
}

I always get the exception that I have to call WebSecurity.InitializeDatabaseConnection first. It looks like I already have so I'm a little confused. Any help would be great. I should mention I'm new to webforms authentication. Thanks for your understanding and answers!


Solution

  • Check out this article on seeding and customizing SimpleMembership. It may give you some hints on proper initialization of the SimpleMembership database. The article discusses modifying how SimpleMembership is initialized that is more straight forward than using the InitializeSimpleMembershipAttribute. You need to have the call to initialize the database in a couple of places because seeding does not always occur and it needs to be in your seed method for it to work. So the safe method is to first check if it has already been initialized before you call it as shown in the following code snippet.

      if (!WebMatrix.WebData.WebSecurity.Initialized)
          WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("SimpleSecurityConnection",
              "UserProfile", "UserId", "UserName", autoCreateTables: true);