Today I experienced the following issue:

I had a class where I would open a SqlConnection, do some actions, and then in the deconstructor I closed the SqlConnection.

~Dumper()
{
    this._sqlConnection.Close();
}

Unfortunately every time my program ran it stopped with this error:

image

Internal .Net Framework Data Provider error 1.

(click to enlarge)

Well it seems that you cannot close a SqlConnection in a ~Deconstructor block.

So the solution is implementing the IDisposable interface

internal class Dumper : IDisposable
{
    private readonly SqlConnection _sqlConnection;

    public Dumper()
    {
        //build and open the connection
        this._sqlConnection = new SqlConnection(Settings.Default.ConnectionString);
        this._sqlConnection.Open();
    }

    /// <summary>
    /// Some function
    /// </summary>
    /// <param name="param">param</param>
    public void SomeFunction(SomeParameter param)
    {
    }

    public void Dispose()
    {
        this._sqlConnection.Close();
    }
}

And to use it you do this:

using (Dumper dumper = new Dumper())
{
    dumper.SomeFunction(myParam);
}

This will cause dumper to be Disposed after the } and it will no longer be available

One Response to “SqlConnection, Close and deconstructor: Internal .Net Framework Data Provider error 1.”
  1. AnzeR says:

    This is right what I was looking for. Thank you for your solution. My DB will be much happier now :D

  2.  
Leave a Reply


And shepherds we shall be, for thee my Lord for thee, power hath descended forth from thy hand, that our feet may swiftly carry out thy command. We shall flow a river forth to thee, and teeming with souls shall it ever be. In nomine Patris, et Filii, et Spiritus Sancti.