Delete SQL connection

I have an SQL class that connects to a database and returns a DataTable. I know that SqlConnection should be removed at the end. I know that this can be done with a block using, but is it also acceptable to call Dispose()inside the destructor of this class?

Herre is my code:

public class SQLEng
{

    //Connection String Property
    //Must be set to establish a connection to the database
    public string ConnectionString{ get; set; }
    SqlConnection _Conn;

    //Overridden Constructor enforcing the Connection string to be set when created
    public SQLEng(string connectionString)
    {
        ConnectionString = connectionString;
        _Conn = new SqlConnection(connectionString);
    }

    //ensure the SqlConnection is disposed when destructing this object
    public ~SQLEng()
    {
        _Conn.Dispose();
    }

    //various other methods to get datatables etc...
}

Basically, I want to have a variable of the SqlConnection class, and not create an instance of SqlConnection inside each method that accesses the database. Is this practice sound?

+3
source share
3 answers

( ) SqlConnection . , , ( ), .

, , ; . , .

+8

Enterprise Library ( MS Patterns and Practices), DAAB .

public virtual int ExecuteNonQuery(DbCommand command)
{
    using (var wrapper = GetOpenConnection())
    {
        PrepareCommand(command, wrapper.Connection);
        return DoExecuteNonQuery(command);
    }
}

protected DatabaseConnectionWrapper GetOpenConnection()
{
    DatabaseConnectionWrapper connection = TransactionScopeConnections.GetConnection(this);
    return connection ?? GetWrappedConnection();
}

, . , , , .

+1

SQL Connection, IDisposable Dispose() Dispose(). :

DbConnection

, - , , , SQL , , . - , .

0

All Articles