Do I need to explicitly open or close connection while query data from database. As what I've noticed is, dapper internally manage the connections while querying, for example -
C#
await _connection.ExecuteAsync(query, new { TenantId = tenantId }).ConfigureAwait(false);
But here the question comes - at what point it closes the connection.
So, confused whether to open n close connection explicitly or let dapper to handle it of its own.
Dapper will close the connection if it needed to open it. So if you're just doing 1 quick query - let Dapper handle it. If you're doing many, you should open (once) and close at the end, with all the queries in the middle...just from an efficiency standpoint.
Here's the relevant code for what you're executing, as an illustration:
c#
bool wasClosed = cnn.State == ConnectionState.Closed;
using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
{
try
{
if (wasClosed) await ((DbConnection)cnn).OpenAsync(command.CancellationToken).ConfigureAwait(false);
var result = await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false);
command.OnCompleted();
return result;
}
finally
{
if (wasClosed) cnn.Close();
}
}
Make sense!!! Thanks for the quick response 馃憤
await _connection.ExecuteAsync(query, new { TenantId = tenantId }).ConfigureAwait(false);
Another question- above implementation is thread safe, right? I mean connection object.
It is if you have multiple connections, or if the connection is MARS enabled (or a non-SQL server equiavlent). That's an ADO.NET provider issue, but Dapper itself has no issues handling the threading here. It's all about if there are any issues with the actual ADO.NET provider running multiple queries on the same connection. For SQL Server, that's MARS.
Thank you 馃憤
Most helpful comment
Dapper will close the connection if it needed to open it. So if you're just doing 1 quick query - let Dapper handle it. If you're doing many, you should open (once) and close at the end, with all the queries in the middle...just from an efficiency standpoint.
Here's the relevant code for what you're executing, as an illustration:
c# bool wasClosed = cnn.State == ConnectionState.Closed; using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader)) { try { if (wasClosed) await ((DbConnection)cnn).OpenAsync(command.CancellationToken).ConfigureAwait(false); var result = await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false); command.OnCompleted(); return result; } finally { if (wasClosed) cnn.Close(); } }