In Dapper, what is the difference between the usage of QueryFirstOrDefault<T>
and ExecuteScalar<T>
?
Both seem to return a single value, although QueryFirstOrDefault<T>
will return a default value for the type, if none is found. Should you always prefer the use of one of the two, due to performance, or other reasons, or are they equivalent, disregarding the default value returned?
The main difference is on their return:
ExecuteScalar<T>
, as other users said, returns only the first cell of the result set.
ExecuteScalar<T>
is generic <T>
, and it automatically casts the result to the type you specified on <T>
QueryFirstOrDefault<T>
executes a query and returns the data type you specified on <T>
:
If the specified type is a basic type (string, int, etc...) it only returns the data from the first column.
If the specified type is an Object, then for each row of the result set an instance of that object is created. Be aware of the fact that a direct column-name===member-name mapping is assumed and no custom mapper can be used so if your object has different field names than the columns of the result set, no values will be fetched.