I\'m creating a database using SQL Server Management Objects.
I wrote the following method to generate a database:
public static void CreateClientDat
In my case it turned out that the problem is not that the newly created database is not ready. But the problem was that SqlConnection.Open()
apparently used a failed cached connection, which then just returned the same error again.
When I call the static SqlConnection.ClearAllPools() method before I try to open the newly created database, it works fine!
See also this question.
A database that has just come online is not necessarily ready to accept connections. To identify when a database can accept connections, query the collation_name column of sys.databases or the Collation property of DATABASEPROPERTYEX. The database can accept connections when the database collation returns a non-null value.
One thing to note here all is that the error message is surrounding security. How are you attempting to logon to the new database (i.e. what type of security is the connection string using for the new database connection)? If you are using SQL authentication you will need to issue sp_adduser to grant the login access to the database.
http://msdn.microsoft.com/en-us/library/ms181422.aspx
You have to approach the database creation a little bit different. The code below handles the database creation correctly. Try it ;)
private void CreateDatabase(string databaseName) { Microsoft.SqlServer.Management.Smo.Server sqlServer = new Microsoft.SqlServer.Management.Smo.Server(_connection); Database createdDatabase = new Database(); createdDatabase.Name = databaseName; createdDatabase.Parent = sqlServer; createdDatabase.Create(); }
In the code below, the _connection is a
Microsoft.SqlServer.Management.Smo.ServerConnectionobject by the way.
[Edit] Modified the code so the exception is not swallowed anymore.