Search code examples
c#mysqldapper

how to return tuple of primitive data types in dapper


I have been using dapper for one of my projects and in one case I wanted to return a tuple of primitive data types. (only a single row) Since I used dapper, I really would like to use dapper for this case also. I checked these links but couldn't find a solution

Can I map a result to Tuple in Dapper?

Dapper multiple objects from one row

Using Dapper to map more than 5 types

This is what my code looks like,

Using(_dbTransaction = _dbConnection.BeginTransaction()){

     var command = new CommandDefinition(
                "SELECT ID1,ID2 " +
                "FROM table " +
                "WHERE ID0 = @ID",
                new {ID = 34},_dbTransaction); //34 is just a number

    var dataSet   = _dbConnection.QueryFirst<Tuple<uint, decimal>>(command);

    //assign the retrieved values to properties of orderItem (orderItem is a passed object as a parameter)
    orderItem.Id = dataSet.item1;
    orderItem.ContainerPrice = dataSet.item2; 

}

but this would generate an exception

{"A parameterless default constructor or one matching signature (System.UInt32 Id, System.Decimal ContainerPrice) is required for System.Tuple`2[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] materialization"}

It would be a great help if can suggest a method or point out where I went wrong


Solution

  • If you want to use a Tuple, you can try this:

        [Test]
        public void TupleTest()
        {
            var result = _connection.Query<int, decimal, Tuple<int, decimal>>
                ("select 1 as Id, 12.99 as ContainerPrice", Tuple.Create, splitOn: "*")
                .FirstOrDefault();
    
            Assert.That(result.Item1, Is.EqualTo(1));
            Assert.That(result.Item2, Is.EqualTo(12.99));
        }
    

    You can also avoid Tuples, and use a dynamic:

        [Test]
        public void DynamicTest()
        {
            var result = _connection.Query<dynamic>
                ("select 1 as Id, 12.99 as ContainerPrice")
                .FirstOrDefault();
    
            Assert.That(result.Id, Is.EqualTo(1));
            Assert.That(result.ContainerPrice, Is.EqualTo(12.99));
        }