SelectCommand.Connection 属性 尚未初始化。 MySql

The SelectCommand.Connection property has not been initialized. MySql

事实证明我正在使用 SignalR,在 html 视图中我向客户端发出以下请求:

 var myHub = $.connection.myHub;
    var direccionWeb = $("#direccionWeb").val().toString();
    $.connection.hub.url = direccionWeb + "/signalr";
    $.connection.hub.start().done(function () {
        myHub.server.broadcastMessageToPrinterReportTicket(global_venta, global_mesa, nombregarzon, idgrupo, grupo);

    }).fail(function (error) {
        console.error(error);
    });

在 Hub 文件中我有以下内容:

public void BroadcastMessageToPrinterReportTicket(String global_venta,String global_mesa,String nombregarzon,String idgrupo, String grupo)
{
    string namePrinter = group;
    DataTable dt = new DataTable();

    string sql = "SELECT " +
        "cant," +
        "det " +
        "FROM producto " +                
        "WHERE venta=@global_venta AND venta>0 AND menu.grupo=@idgrupo AND comandasd.pedido=0";
    conexion.conectar(); 

    using (MySqlCommand command = new MySqlCommand(sql, conexion.con))
    {
        command.Parameters.AddWithValue("@global_venta", global_venta);
        command.Parameters.AddWithValue("@idgrupo", idgrupo);
        using (MySqlDataAdapter reader = new MySqlDataAdapter(command))
        {
            using (MySqlDataAdapter sda = new MySqlDataAdapter(command))
            {
                sda.Fill(dt);
            }
        }
    }
    conexion.cerrar();


    Clients.All.printReport(datos, ........);
}

包含连接 class 的文件如下:

public void conectar()
{
    try
    {
        string ip = HttpContext.Current.Session["ip"].ToString();
        string db = HttpContext.Current.Session["db"].ToString();
        string user = HttpContext.Current.Session["user"].ToString();
        string pass = HttpContext.Current.Session["pass"].ToString();

        con = new MySqlConnection("server=" + ip + ";user id=" + user + ";password=" + pass + ";database=" + db + ";port=3306;Allow User Variables=true"); 
        con.Open();
    }
    catch
    {

    }
}

但是当我尝试向DataTable添加数据时,也就是在sda.Fill(dt)说的那一行,出现如下错误:SelectCommand.Connection 属性 has尚未初始化。

奇怪的是,当我使用它时,它与在控制器中声明的功能相同,它可以正常工作。我想要的是能够获得一个带有 BroadcastMessageToPrinterReportTicket 接收的参数的数据表并将其发送给客户端。

如果有人知道如何更正错误或提供帮助,我们将不胜感激。

问候

the SelectCommand.Connection property has not been initialized

需要设置MySqlCommand.Connection 属性才能使用命令。异常告诉您它尚未设置。

您正在使用设置它的构造函数:

using (MySqlCommand command = new MySqlCommand(sql, conexion.con))

逻辑推论是conexion.con == null.

我们看到 con 设置在 conectar 中。但是,该代码周围有一个 try/catch 块。因此,一定是在分配 con 之前抛出(并忽略)异常。

最可能的解释是 HttpContext.Current.Session["..."] 值中的一个(或多个)是 null,因此对其调用 .ToString() 会抛出 NullReferenceException

建议:

  1. 不要捕获和忽略异常;它们通常表示需要正确处理的实际问题。
  2. 会话状态似乎是存储数据库凭据的一个非常奇怪的地方;考虑改用 web.config 设置。 (或者您可能希望先对它们进行硬编码,看看是否可以让其余代码正常工作,然后在确定其他所有内容都正确后将它们移至 Settings。)