Skip to content

3.3. Working with tuple type parameters

Vedran Bilopavlović edited this page Dec 28, 2020 · 3 revisions

Working with tuple type parameters

Important notes when mapping tuple types:

  1. Mappings are always by position, not by name.
  1. All database nulls are automatically converted to null where applicable. Use nullable types to avoid errors. For example DateTime? or bool?.

Single record example

using System.Linq;

//...
var SQL = "SELECT FirstName, BirthDate FROM Employees where EmployeeID = 1";
var first = connection.Read<(string FirstName, DateTime BirthDate)>(sql).Single();
Console.WriteLine($"{first.FirstName.Trim()} birth date = {first.BirthDate}"); // Nancy birth date = 12/08/1968 00:00:00

Try it yourself

Iterate values example

foreach(var name in connection.Read<(string First, string Last)>("SELECT TOP 10 FirstName, FirstName FROM Employees"))
{
    Console.WriteLine($"{name.First.Trim()} {name.Last.Trim()}");
}

Try it yourself

Build dictionary example

using System.Linq;

//...
var dict = connection.Read<(int Id, string Name)>("SELECT ProductID, ProductName FROM Products").ToDictionary(t => t.Id, t => t.Name);
foreach(var (key, value) in dict)
{
    Console.WriteLine($"{key} {value.Trim()}");
}

Try it yourself

Multiple instances mapping example

var sql = "SELECT LastName, FirstName, BirthDate, Notes FROM Employees where EmployeeID = 1";
var (name1, personal1) = connection.Read<(string Last, string First), (DateTime Birth, string Notes)>(sql).Single();
Console.WriteLine($"{name1.First.Trim()} {name1.Last.Trim()} born {personal1.Birth} has notes {personal1.Notes}");

Try it yourself

For more information and options when working with parameters see also

For more information and options when working with parameters see also

See also