Dapper - QueryFirst

Description

QueryFirst 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.

The result can be mapped to:

Parameters

The following table shows the different parameters of a QueryFirst method.

NameDescription
sqlThe query to execute.
paramThe query parameters (default = null).
transactionThe transaction to use (default = null).
commandTimeoutThe command timeout (default = null)
commandTypeThe command type (default = null)

First, Single & Default

Be careful to use the right method. First & Single methods are very different.

ResultNo ItemOne ItemMany Items
FirstExceptionItemFirst Item
SingleExceptionItemException
FirstOrDefaultDefaultItemFirst Item
SingleOrDefaultDefaultItemException

Example - Query Anonymous

Execute a query and map the first result to a dynamic list.

  1. string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
  2. using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
  3. {
  4. var orderDetail = connection.QueryFirst(sql, new {OrderDetailID = 1});
  5. FiddleHelper.WriteTable(orderDetail);
  6. }

Try it: .NET Core | .NET Framework

Example - Query Strongly Typed

Execute a query and map the first result to a strongly typed list.

  1. string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
  2. using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
  3. {
  4. var orderDetail = connection.QueryFirst<OrderDetail>(sql, new {OrderDetailID = 1});
  5. FiddleHelper.WriteTable(orderDetail);
  6. }

Try it: .NET Core | .NET Framework