views:

50

answers:

3

The following code example fails randomly on some PC's. On other PC's the problem cannot be reproduced. All PC's are running .NET 3.5 SP1 on Vista SP1.

string connection = @"Data Source=PCNAME\SQLEXPRESS;Database=TestDatabase ;User Id=sa;Password=ThePassword;";

TestDatabase db = new TestDatabase (connection);

if (!db.DatabaseExists())
{
    db.CreateDatabase();
}

DatabaseExists() returns false but CreateDatabase() throws this Exception:

System.Data.SqlClient.SqlException: Database 'TestDatabase ' already exists. Choose a different database name.

The documentation states that DatabaseExists() returns true if the database exists and can be opened.

What could cause the database not to be available?

+2  A: 

It could be a rights issue, i.e. the database exists but you don't have permission to open it. That would return a false and also the exception you provided.

Lazarus
The strange thing is that the problem comes and goes on some machines. I.e. one moment it fails the next its succeeds.
Fedearne
Is that on successive executions of your code, without doing anything (and I mean anything) in between? If so then it's very odd indeed.
Lazarus
I do during startup of an application. If i get the error - i just restart the application and i usually works right away.
Fedearne
Very odd, it's effectively looking as though `DatabaseExists` is nondeterministic.
Lazarus
A: 

Just created a simple Windows Application with the following code...

       string connection = @"Data Source=.\SQLEXPRESS;Database=TestDatabase;Integrated Security=True";

        LinqToSQLDataContext dc = new LinqToSQLDataContext(connection);

        if (!dc.DatabaseExists())
        {
            dc.CreateDatabase();
        }

Ensure that there was no database with the name TestDatabase. As the code works as expected. The only difference in my case is that I am use Integrated Security. Of course, this is not the complete code, and I would get an error as expected at dc.CreateDatabase as follows...

alt text

Hence, I can confirm that the code is good. It looks like you don't have enough perms on the server.

Rahul Soni
A: 

Could it be a multi-user race condition?

User1: test database existance (false)
User2: test database existance (false)
User1: create database
User2: create database (exception!)
David B
It's a good theory, but the database already exists, when the app starts.
Fedearne