Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should dapper use a "using" statement?

I have seen examples where someone is doing:

IDbConnection db = new MySqlConnection(conn);

var people = db.Query<People>("SELECT * FROM PEOPLE").ToList();

or is the above a bad practice and should all queries be put in using statements like so:

using (var db = new MySqlConnection(conn))
{
var people = db.Query<People>("SELECT * FROM PEOPLE").ToList();
}
like image 556
xaisoft Avatar asked Mar 11 '15 01:03

xaisoft


People also ask

Does Dapper use connection pooling?

Here we are creating the connection by 'using'. So every time it will create a new connection instead of reusing the existing connection. We are not adhering to the connection pooling. But the reality is, as we discussed earlier, Dapper is a mapping library.

Does Dapper use SqlClient?

SqlClient and SqlConnection , but Dapper supports other databases that use the DbConnection abstraction. We also need a projection class representing the results of our SQL query.

Why should I use Dapper?

Dapper is super awesome to handle complex queries that sport multiple joins and some real long business logic. Entity Framework Core is great for class generation, object tracking, mapping to multiple nested classes, and quite a lot more.

Is Dapper case sensitive?

Dapper's(SqlMapper) Query method over the Connection factory runs the SQL query, then maps the database result to Employee class and returns as a list of employees. Note : Only matching class and table properties are mapped to list of employee, they are case sensitive.


1 Answers

As others have correctly noted, the best practice in general is to use using any time an object implements IDisposable and you know that the lifetime of the object is going to be short -- that is, not longer than the duration of the current method. Doing so ensures that scarce operating system resources are cleaned up in a timely manner. Even if an object's disposal is "backstopped" by its finalizer, you don't want to be in a situation where, say, you have a lock on a file or database or something that is not going to be released until the finalizer runs several billion nanoseconds from now.

However I would temper that advice by saying that there are a small number of types that implement IDisposable for reasons other than timely disposal of unmanaged resources. In some very specific cases you can safely skip the using. However, it is almost never wrong to use using, even when it is not strictly speaking necessary, so my advice to you is to err on the side of caution and over-use, rather than under-use using.

like image 96
Eric Lippert Avatar answered Sep 20 '22 06:09

Eric Lippert