Michael Trullas
Michael Trullas

Reputation: 664

How does internally QuerySingle or QueryFirst in Dapper work?

I see that Dapper has QuerySingle and QueryFirst methods. Does QuerySingle check that the sql returns only one row and maps that? Does QueryFirst returns the first row mapped independently how many rows there are?

If I want to make an any query, like anyItemSold:

Select Top 1 1 From Items Where IsSold = 1

Would I have to write it like this and maybe use ExecuteScalar?

Upvotes: 10

Views: 10819

Answers (1)

Amit Joshi
Amit Joshi

Reputation: 16389

The First, Single & Default work the same way with Dapper the way it works generally.

Please refer to this tutorial:

QuerySingle method is an extension method that can be called from any object of type IDbConnection. It can execute a query and map the first result and throws an exception if there is not exactly one element in the sequence.

Also, the same tutorial provide simple table to understand how they work:

Image

About ExecuteScalar:

It executes the query, and returns the first column of the first row in the result set returned by the query. The additional columns or rows are ignored.

If your query return single value (single column of single row) then this is best choice.

Upvotes: 13

Related Questions