C# – Comparing QUERY and EXECUTE in Dapper

cdapper

I would like to ask if what is the best to use when INSERTING, UPDATING, DELETING, REMOVING, QUERY SPECIFIC DATA using DAPPER? I'm really confused in using EXECUTE and QUERY command in DAPPER..

Best Answer

This should not be confusing at all, especially if you look at the signature of the methods exposed by the Dapper (as per documentation):

public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

Query method is specifically meant for executing a select statement internally, which can return the IEnumerable of a type T, there are options to execute it, if done using anonymous parameter, then you are not expecting any return value or Output parameter, it just takes input parameter and provide the result, which has schema matching to the properties of Type T. In case return value or Output parameter is required, then that needs to be bound using DynamicParameters

public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Execute method is meant for executing the DML statements, like Insert, Update and Delete, whose purpose is to make changes to the data in the database. The return type is an integer, which should contain the value of number of rows updated, if in SQL Server we have set Set RowCount On, this call will not help in returning the Result Set, its only for DML calls.

In case you need multiple result set then we have QueryMultiple. which returns a GridReader and can be used to return the result of multiple Select statements, using a concept of MARS (Multiple active result set).

Practically if your aim is just to execute a procedure, any of them would do, but what is more important is what result set are looking forward to receive, they all have different return to provide results