1
votes

Having difficulty figuring out why my database will not seed:

Here is what I have in my Global.asax code:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

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

        Database.SetInitializer(new DataContextInitializer());
        DataContext db = new DataContext();
        db.Database.Initialize(true);

        WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);

    }

and here is the DataContextInitializer:

public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
 {
    protected override void Seed(DataContext context)
    {
        if (!WebSecurity.Initialized)
        {
            WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);
            WebSecurity.CreateUserAndAccount("admin", "12345");
        }

        var roles = (SimpleRoleProvider)Roles.Provider;
        var membership = (SimpleMembershipProvider)Membership.Provider;

        if (!roles.RoleExists("admin"))
        {
            roles.CreateRole("admin");
        }
        if (membership.GetUser("admin", false) == null)
        {
            membership.CreateUserAndAccount("admin", "12345");
        }
        if (!roles.GetRolesForUser("admin").Contains("admin"))
        {
            roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" });
        }
    }
}

While debugging, the SqlException that I get is "There is already an object named ... in the database." Any idea why this would occur?

1

1 Answers

1
votes

These are the steps I took:

  • Copied seed logic to the Migrations Configuration.cs file.
  • Excluded an old migration from the project
  • Within package console manager performed add-migration and gave it a name
  • Then ran update-database -verbose -force AFTER making sure that WebMatrix.WebData reference properties had 'CopyLocal = true'

I hope this helps someone.