Can I map a result to Tuple in Dapper?
This works starting from C# 7. This is a Value Tuple
public (int Id, DateTime? PublishDate) GetItem(string id)
{
const string sqlCommand = "select top 1 Id, PublishDate from Item where Id = @id";
return _connection.Query<(int, DateTime?)>(sqlCommand, new { id }).FirstOrDefault();
}
Using the method
var item = GetItem(123);
Console.WriteLine($"The publish date of item [{item.Id}] is [{item.PublishDate.Value}]");
Make sure you have installed Dapper 1.50.4 or later.
Here is a working example:
public class DapperTests
{
[Test]
public void TuppleTest()
{
var conn = new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=mydb");
conn.Open();
var result = conn.Query<int, int, Tuple<int, int>>(
"select 1,2 union all select 4,5", Tuple.Create, splitOn: "*").ToList();
conn.Close();
Assert.That(result.Count, Is.EqualTo(2));
}
}