In Dapper, what is the difference between the usage of
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.
<T>, and it automatically casts the result to the type you specified on
QueryFirstOrDefault<T> executes a query and returns the data type you specified on
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.
Scalar expects there to only be a single row returned from the SQL script; QueryFirstOrDefault doesn't care how many rows are returned.
I think (can't check this right now) that Scalar might throw an error if zero rows are returned (thanks @Tim for correcting me on multiple results).
I'd say the preference depends on what the script you've written is expected to do.