'connection.ServerVersion' 引发了 'System.InvalidOperationException' 类型的异常

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

我在 C# Winforms 应用程序中尝试 SQL 服务器连接时在 VS 中收到此错误。

我正在使用 Microsoft.Data.SqlClient

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnectionStringBuilder build = new SqlConnectionStringBuilder("Server = {ServerName},1433; Initial Catalog = {Database}; Persist Security Info = False; User ID = {Username}; Password = {Password}; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Authentication = Active Directory Password");

        using (SqlConnection connection = new SqlConnection(build.ConnectionString))
        {
            string sql = $"SELECT ItemID, Barcode FROM dbo.TEST_Barcode WHERE Barcode = 9323503022494";
         
            using (SqlCommand command = new SqlCommand(sql, connection)) 
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    // This is where the error occurs
                    connection.Open(); 

                    while (reader.Read())
                    {
                        textBox1.Text = reader.GetValue(0).ToString(); 
                    }
                }
            }
        }
    }
    catch (SystemException)
    {
    }
}

以上将 return 无论连接在哪里都会出错。

问题是:

VSC和VS终端应用成功代码如下:

using System;
using Microsoft.Data.SqlClient;

public class Program
{
    public static void Main()
    {
        long barcode;
        string barcodeText;

        Console.WriteLine("Enter in a barcode to find: ");
        barcodeText = Console.ReadLine();
        barcode = Convert.ToInt64(barcodeText);

        try
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder("Server=tcp:{server},1433;Initial Catalog={database};Persist Security Info=False;User ID={username};Password={password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication=Active Directory Password");

            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                string sql = $"SELECT ItemID, Barcode, SOH FROM dbo.TEST_Barcode WHERE Barcode = {barcode}";

                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                    while (reader.Read())
                        {
                            Console.WriteLine("{0} {1} {2}", reader.GetString(0), reader.GetString(1), reader.GetInt32(2));
                        }
                    }
                }
            }   
        }
        catch (SqlException e)
        {
            Console.WriteLine(e.ToString());
        }
        Console.ReadLine();
    }
}

上面的输出:

Enter in a barcode to find: 
9323503022494

100003 9323503022494 5

根据我在 MS 文档中找到的内容,当连接关闭时会发生这种情况,但为什么这会在 VSC + VS 终端中工作而在 Winforms 应用程序中失败?

如有任何帮助,我们将不胜感激

谢谢!

试试@AlwaysLearning 的这个建议

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnectionStringBuilder build = new SqlConnectionStringBuilder("Server = {ServerName},1433; Initial Catalog = {Database}; Persist Security Info = False; User ID = {Username}; Password = {Password}; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Authentication = Active Directory Password");

        using (SqlConnection connection = new SqlConnection(build.ConnectionString))
        {
            string sql = $"SELECT ItemID, Barcode FROM dbo.TEST_Barcode WHERE Barcode = 9323503022494";
         
            using (SqlCommand command = new SqlCommand(sql, connection)) 
            {

                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        textBox1.Text = reader.GetValue(0).ToString(); 
                    }
                }
            }
        }
    }
    catch (SystemException)
    {
    }
}