MiddleKay
MiddleKay

Reputation: 319

Incorporating WCF with SQL to MVC

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>

Upvotes: 1

Views: 182

Answers (1)

Chris
Chris

Reputation: 2481

   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

Upvotes: 1

Related Questions