Can I use this approach efficiently?
using(SqlCommand cmd = new SqlCommand(\"GetSomething\", new SqlConnection(Config.ConnectionString))
{
cmd.Connection
I use this pattern. I have this private method somewhere in my app:
private void DisposeCommand(SqlCommand cmd)
{
try
{
if (cmd != null)
{
if (cmd.Connection != null)
{
cmd.Connection.Close();
cmd.Connection.Dispose();
}
cmd.Dispose();
}
}
catch { } //don't blow up
}
Then I always create SQL commands and connections in a try block (but without being wrapped in a using block) and always have a finally block as:
finally
{
DisposeCommand(cmd);
}
The connection object being a property of the command object makes a using block awkward in this situation - but this pattern gets the job done without cluttering up your code.