1

I get this error on runtime:

System.InvalidOperationException: ExecuteReader: Connection property has not been initialized.

which is pointing to this line:

SqlDataReader openBuyers = b.ExecuteReader();

I'm using a method from my WCF.

This on svc:

public string ConnectionString()
    {
        string connectToDB = ConfigurationManager.ConnectionStrings["connection"].ToString();
        return connectToDB;
    }

    public SqlConnection OpenConnection()
    {
        try
        {
            SqlConnection linkToDB = new SqlConnection(ConnectionString());
            linkToDB.Open();
            return linkToDB;
        }
        catch (Exception)
        {
            return null;
        }
    }

Added this to my web.config in WCF:

<connectionStrings>
     <add name="connection" connectionString="Data 
     Source=localhost\SQLEXPRESS;Integrated Security=true;Initial
     Catalog=ProductDB"/>
</connectionStrings>
MiddleKay
  • 319
  • 4
  • 13

1 Answers1

1
   SqlConnection myConnection = new SqlConnection(myConnectionString);
   SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
   myConnection.Open();
   SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

You're missing the top 3 lines - not creating or opening your connection

Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader(v=vs.71).aspx

Chris
  • 2,471
  • 25
  • 36
  • Of course I have those: linkToDB = ecom.OpenConnection(); SqlCommand b = new SqlCommand(sqlText, linkToDB); where ecom is the instance of my web service, tried yours but error was Instance failure. pointing to myConnection.Open(); – MiddleKay Aug 02 '12 at 09:47
  • whats the ecom object? is it returning a new connection or re-using one? – Chris Aug 02 '12 at 11:33
  • MyServiceclient ecom = new MyServiceClient(); It is reusing from the web service. – MiddleKay Aug 02 '12 at 13:57
  • I would have thought you'd need a new connection each time...? that OpenConnection() call is not providing a connection - thats what your error is saying, can you post up the OpenConnection() code? – Chris Aug 02 '12 at 14:54
  • I would look at this: http://stackoverflow.com/questions/251603/passing-db-connection-object-to-methods and reconsider your design slightly? – Chris Aug 03 '12 at 06:46