visual-studiowcfappharbor

How to SELECT * from an wcf application, database hosted in appharbor


this is my first time playing with WCF in visual studio (2015), and I am running into some problems. I have my database hosted in appharbor. I managed to insert new items into the database with:

    public Test Insert (Test TestTable)
    {
        SqlConnection conGet = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(connectionString, conGet);
        cmd.Parameters.AddWithValue("@testID", testTable.testID);
        cmd.Parameters.AddWithValue("@testName", testTable.testName);

        conGet.Open();
        cmd.CommandText = "INSERT INTO TestTable (testID, testName) VALUES (@testID, @testName)";
        cmd.ExecuteScalar();
        conGet.Close();
        return testTable;
    }

PROBLEM: when I tried to select from it:

    public Test GetData(Test test)
    {
        SqlConnection conPut = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("SELECT * FROM TestTable", conPut);
        conPut.Open();
        SqlDataReader rd = cmd.ExecuteReader();
        if (rd.Depth>0)
        {
            while (rd.Read())
            {
                test.testID = (int)rd["testID"];
                test.testName = rd["testName"].ToString();
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        conPut.Close();
        return test;
    }

rd (SqlDataReader) is not reading anything and just returns a null value, even though the test table has rows in it.

Please give me some pointers? I have tried several methods online, and no luck.. Thank you!


Solution

  • Remove that test for Depth. The Sql DataProvider doesn't support that property. It is always zero

    Source: MSDN SqlDataReader.Depth

    The outermost table has a depth of zero. The .NET Framework Data Provider for SQL Server does not support nesting and always returns zero.

    If you want to test the condition of no rows then use the property HasRows

    SqlDataReader rd = cmd.ExecuteReader();
    if (rd.HasRows)
    {
        while (rd.Read())
        {
            test.testID = (int)rd["testID"];
            test.testName = rd["testName"].ToString();
        }
    }
    else
    {
        Console.WriteLine("No rows found.");
    }