Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper materializing to a Tuple

I need return a list from dapper with the new tuple in C# 7.

public static List<(int StyleId, decimal StyleCode)> GetOnlyServices()
{
    var query = $@" SELECT
                    ST.style_id as StyleId, ST.style_code as StyleCode
                    ...
                    ...";

    using (SqlConnection db = new SqlConnection(InfobaseConString))
    {
        var a = db.Query<(int StyleId, decimal StyleCode)>(query, commandTimeout: 90).ToList();
        return a;
    }
}

But this function only return me 56 rows with (0,0), Item1=0, Item2=0. What I missing?

like image 695
Yuri Morales Avatar asked Jan 12 '17 16:01

Yuri Morales


2 Answers

Looks like they added this a few months ago. Here's an example usage from the tests:

    [Fact]
    public void TupleReturnValue_Works_NamesIgnored()
    {
        var val = connection.QuerySingle<(int id, string name)>("select 42 as [Item2], 'Fred' as [Item1]");
        Assert.Equal(42, val.id);
        Assert.Equal("Fred", val.name);
    }
like image 165
John Tseng Avatar answered Nov 01 '22 04:11

John Tseng


Frankly, it's just not supported the way the tuples work. Dapper's deserializer maps column values with constructor parameters or properties/fields by name in the object's type. (Source if you can understand the generated IL).

ValueTuples on the other hand still only have property names corresponding to items in the tuple (Item1, Item2, etc.) but uses compiler/ide magic to make them accessible by other names. So StyleId or StyleCode will not be actual property names, they're just aliases for Item1 and Item2 respectively.

You'll either have to wait for the team to add in explicit support for ValueTuples or use the expected property names in your query.

var query = $@" SELECT
                ST.style_id as Item1, ST.style_code as Item2
                ...
                ...";
like image 45
Jeff Mercado Avatar answered Nov 01 '22 05:11

Jeff Mercado