Search code examples
c#sql-serverado.netdatabase-connectionadventureworks

ServerVersion throws 'System.InvalidOperationException' when trying to connect to local database in SQL Server


I'm trying to exercise the ADO.net framework, and I'm in the very beginning. I'm trying to connect to my local database using the following string:

connectionString="Server=localhost;Database=AdventureWorks2012; Integrated Security=True;"

But when I try to use a button I created to access the database, I get this error

The interesting part is that before I use the button, everything is all right, as I saw through debugging and breaking right after

conn.Open(); 

(ServerVersion doesn't throw an exception yet, instead it returns the version "11.00.3153" )

With the exception of the connection string, I'm really pretty sure the code is correct, so I think the problem is configuration related. Any ideas?

The event for when the code breaks is:

private void buttonGetEmployee_Click(object sender, EventArgs e)
    {
        try
        {
            DataLayer.Employees es = new DataLayer.Employees();
            DataLayer.Employee employee = es.GetEmployee(int.Parse(textBoxEID.Text));

            textBoxFName.Text = employee.FirstName;
            textBoxLName.Text = employee.LastName;
            textBoxDName.Text = employee.DepartmentName;

        }
        catch { }

Solution

  • I just discovered the problem. In

    public class Employees{...}
    

    the associated command

    cmd.CommandText = @"MyQuery";
    

    was badly defined, not containing the expected properties, and because of that it returned the wrong object for the event showed in the question, the

    buttonGetEmployee_Click(object sender, EventArgs e)
    

    This lead to the error you saw, which may seem related to ServerVersion but indicated in fact an error occuring when the event was called to use the object

    Employees es