Dapper - Result Strongly Typed

Description

Extension methods can be used to execute a query and map the result using strongly typed.

The anonymous result can be mapped from following methods:

These extension methods can be called from any object of type IDbConnection.

Example - Query

Query method can execute a query and map the result to a strongly typed list.

Example
string sql = "SELECT * FROM OrderDetails";

using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
	connection.Open();
	
	var orderDetails = connection.Query<OrderDetail>(sql).ToList();

	Console.WriteLine(orderDetails.Count);
}

Try it online

Example - QueryFirst

QueryFirst method can execute a query and map the first result to a strongly typed list.

Example
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";

using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
	connection.Open();
	
	var orderDetail = connection.QueryFirst<OrderDetail>(sql, new {OrderDetailID = 1});

	Console.WriteLine(orderDetail.Quantity);
}

Try it online

Example - QueryFirstOrDefault

QueryFirstOrDefault method can execute a query and map the first result to a strongly typed list, or a default value if the sequence contains no elements.

Example
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";

using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
	connection.Open();
	
	var orderDetail = connection.QueryFirstOrDefault<OrderDetail>(sql, new {OrderDetailID = 1});

	Console.WriteLine(orderDetail.Quantity);
}

Try it online

Example - QuerySingle

QuerySingle method can execute a query and map the first result to a strongly typed list, and throws an exception if there is not exactly one element in the sequence.

Example
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";

using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
	connection.Open();
	
	var orderDetail = connection.QuerySingle<OrderDetail>(sql, new {OrderDetailID = 1});

	Console.WriteLine(orderDetail.OrderDetailID);
}

Try it online

Example - QuerySingleOrDefault

QuerySingleOrDefault method can execute a query and map the first result to a strongly typed list, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

Example
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";

using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
{
	connection.Open();
	
	var orderDetail = connection.QuerySingleOrDefault<OrderDetail>(sql, new {OrderDetailID = 1});

	Console.WriteLine(orderDetail.OrderDetailID);
}

Try it online