I have some instances where sometimes I want to execute code within the same connection (for using temp tables, etc), but most of the time I want to open and close the connection as soon as possible.
public int BulkInsert<T>(IDataReader dataReader, Dictionary<string, string> columnMappings = null, int timeoutInSeconds = 120)
{
if (_sqlConnection != null)
{
return BulkInsert<T>(dataReader, _sqlConnection, columnMappings, timeoutInSeconds);
}
using (var tempConnection = new SqlConnection(_connectionString))
{
return BulkInsert<T>(dataReader, tempConnection, columnMappings, timeoutInSeconds);
}
}
How can I make this code more clean and not two separate calls?
My attempt:
public int BulkInsert<T>(IDataReader dataReader, Dictionary<string, string> columnMappings = null, int timeoutInSeconds = 120)
{
var rv = 0;
var conn = _sqlConnection ?? new SqlConnection(_connectionString);
try {
rv = BulkInsert<T>(dataReader, conn, columnMappings, timeoutInSeconds);
} finally {
if (conn != _sqlConnection)
{
conn.Dispose();
}
}
return rv;
}
but I am not really happy with it.
P.S. I wasnt sure if this belonged to stackoverflow or programming but I figured because the use of using
that it was pretty c# specific and more of a refactor than just an opinion of style