views:

564

answers:

3

Hi,

I am getting this "cannot open user default database. login failed" error. What I did was using ORM to create DataContext, in the code first call TableExists function to check if the version_tbl existed, if not, then call scripts to exec sql commands to create version_tbl. Then create a new dataContext, but problem is after the call I am getting this error on dataContext entity. If I remove the TableExists call, then dataContext creation is fine or move the dataContext creation before the TableExists call, but then the problem occurs in the TableExists call when it tries to connect. Seems like I can only connect once. Anyway I can call TableExists then able to create dataContext?

Below is my code sample

static bool TableExists(string tableName) {

        using (SqlConnection connection = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=planning;Integrated Security=True"))
        {

            string checkTable =

               String.Format(

                  "IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'",

                  tableName);



            SqlCommand command = new SqlCommand(checkTable, connection);

            command.CommandType = CommandType.Text;

            connection.Open();

            bool retVal = Convert.ToBoolean(command.ExecuteScalar());                

            return retVal;

  }

}

myFunc ()
{
if (!TableExists ("version_tbl"))
{
// call scripts to create version_tbl
}

DataContext ctx = new DataContext ();
A: 

Before everything else did you check if your domain user has the appropriate DB rgihts? Try to validate the DB connection first.

Shankar Ramachandran
A: 

You should be able to open two connections to the database at the same time: 1 through ADO.NET and 1 through LinqToSql.

The format of your code as displayed by StackOverflow is difficult to read, but it appears that you are returning from your TableExists method before the using statement is able to close the connection. Does it make any difference if you change that?

Are you getting different errors depending on which order you open the connections or is it always the same error?

Michael Maddox
The close makes no difference and with same errorSystem.Data.SqlClient.SqlException was caught Message="Cannot open user default database. Login failed.\r\nLogin failed for user" Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=11 LineNumber=65536 Number=4064 Procedure="" Server="\\\\.\\pipe\\62547E80-CB39-45\\tsql\\query" State=1
queandans
A: 

Don't stop with the Exception. Go to the database and check the message in the log. The exceptions for LOGIN's are not clear on purpose for security reasons, but the log should have a better explanation of what happened.

Nestor

related questions