Pregunta

I am currently working on a Node.js server. This server uses Edge.js to execute my C# workflow code (it is a dll).

We are using a custom written logging dll that logs to a SQL Server table. Node.js and my Workflow dll use this logging dll to log steps to the SQL databse. Ideally it would just need to open the connection to the SQL database once and then reuse it for Node and Edge/c# code.

Is there some way of opening the connection in the Node.js code and then passing that connection handle around to Edge/C#. Or is there a better way to do this?

At the moment I am just opening the connection when I call my c# Workflow dll and then closing it at the end. Doing this in Node causes some problems (assuming because of async code) "System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is open.".

¿Fue útil?

Solución

It is a bad idea to pass SqlConnections around. partly because they are a relatively expensive resource and you may have a limited number of them available. The underlying database drivers will automatically cache SqlConnections for you (AFAIK this uses the connection string as the key for the cache, so always use the same connection string for the same data source).

You should also use the using statement to ensure SqlConnections are disposed in a timely fashion, when you no longer need them. E.g., wrap your call to ExecuteNonQuery with a using statement that creates/opens the SqlConnection:

using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
    sqlConnection.Open();
    // Need to define cmdText.
    string cmdText = "";
    using (SqlCommand sqlCommand = new SqlCommand(cmdText, sqlConnection))
    {
        sqlCommand.CommandType = CommandType.Text;
        sqlConnection.Open();
        var result = sqlCommand.ExecuteNonQuery();
        sqlConnection.Close();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top