Search code examples
c#databasevisual-studiosql-server-2008invalid-object-name

Visual C# SQL Server Northwind Database Error: Invalid Object Name 'dbo.Products'


My issue is that I keep getting an error on console that says

Invalid Object Name 'dbo.Products'

I am using Visual C# 2008 Express Edition and SQL Server 2008 Express.

I have had some issue with preparing/installing the Northwind sample database, so I'm unsure if that has any weight on the issue though. Our teacher gave a test program which is the program I am receiving this error.

static void Main()
{
    string connectionString =
            "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server  2000 Sample Databases\\PUBS.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";

    string queryString =
        "SELECT ProductID, UnitPrice, ProductName FROM dbo.Products "
            + "WHERE UnitPrice > @pricePoint "
            + "ORDER BY UnitPrice DESC;";

    int paramValue = 5;

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Parameters.AddWithValue("@pricePoint", paramValue);

        try
        {
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine("\t{0}\t{1}\t{2}",
                    reader[0], reader[1], reader[2]);
            }

            reader.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.ReadLine();
    }
}

Solution

  • Your database is not Northwinds but Pubs.

    Check the Connection String

     string connectionString =
            "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server  2000 Sample Databases\\PUBS.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
    

    Specifically on AttachDBFileName:

    AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server  2000 Sample Databases\\PUBS.MDF
    

    Try to change it to Northwinds (given it is in the same folder as Pubs), like:

    AttachDbFilename=C:\\Users\\Andrew\\Desktop\\SQL Server  2000 Sample Databases\\Northwind.MDF
    

    Update:

    Try to use SqlCeConnection instead of Sqlconnection because it looks like you are using compact or SDF:

     using (SqlConnection connection =
        new SqlConnection(connectionString))
    

    To:

     using (SqlCeConnection connection =
        new SqlCeConnection(connectionString))