SB2055
SB2055

Reputation: 12852

Cannot delete database because it is in use (with Membership)

I'm trying the following in my EF codefirst Seed method:

protected override void Seed(TestDbContext context)
        {
            SqlConnection.ClearAllPools();
            context.Database.Delete();
            context.Database.CreateIfNotExists();

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

This fails with the error 'cannot delete because the database is currently in use'. It seems to only happen after I run my Api project, which initializes its own connection to the membership tables:

private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }
                    if (!WebMatrix.WebData.WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId",
                                                                 "UserName", autoCreateTables: true);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }

Any idea how I can get this working from code (I'm trying to get testing automated)?

Upvotes: 0

Views: 992

Answers (1)

Lotok
Lotok

Reputation: 4607

On the server explorer, right click your data connection to that db and choose close connection.

Upvotes: 1

Related Questions