Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does internally QuerySingle or QueryFirst in Dapper work?

Tags:

c#

dapper

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?

like image 755
Michael Trullas Garcia Avatar asked Apr 25 '26 06:04

Michael Trullas Garcia


1 Answers

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.

like image 93
Amit Joshi Avatar answered Apr 26 '26 18:04

Amit Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!