Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when opening an sql connection: 'MyConnection.ServerVersion' threw an exception of type 'System.InvalidOperationException'

I have seen this problem in many posts, but cannot fix.. I'm trying to connect to a table in my SQL DB, using visual Studio 2015 (C#), and keep on getting an error.
This is my code (note: the connection string was taken from appsettings.json file):

 string ConnectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet5-LicenseTool-b66aeae7-0f53-4987-8e86-6fba8a7f5e16;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
 using (SqlConnection MyConnection = new SqlConnection(ConnectionString))
 {
     // some code here 
 }

... when I run I get an error of:

'MyConnection.ServerVersion' threw an exception of type 'System.InvalidOperationException'

See attachments of error and of server data - You can see I'm connected and I have correct parameters.

Error Message

Server

like image 582
Abigail Avatar asked Dec 31 '25 02:12

Abigail


1 Answers

Your error message clearly states Invalid operation. The connection is closed.. This means that you didn't Open() the connection. Use this:

string ConnectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet5-LicenseTool-b66aeae7-0f53-4987-8e86-6fba8a7f5e16;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (SqlConnection MyConnection = new SqlConnection(ConnectionString))
{
    MyConnection.Open();
    // some code here 
}
like image 118
RePierre Avatar answered Jan 02 '26 16:01

RePierre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!