Can I map a result to Tuple in Dapper?

后端 未结 5 1351
梦谈多话
梦谈多话 2021-01-01 08:49

I am trying to select a list of 2 integer columns map the results to a Tuple. Just as an example:

return connection.Query>(\"sele         


        
5条回答
  •  悲&欢浪女
    2021-01-01 09:30

    Tuple is one option, I prefer using a dynamic result whenever I do not want to create a class, i.e.,

    string sql = "Select 'f' as Foo, 'b' as Bar";
    
    var result = connection.Query(sql).Single();
    
    string foo = result.Foo;
    string bar = result.Bar
    

    The name of the field returned from the result will be the name of the dynamic property.

    In your case, you are wanting to return a list and not assign to single variables, so a Tuple would be more appropriate:

    string sql = "select id1, id2 from sometable";
    
    List> result = conn.Query>( // *1
        sql,
        Tuple.Create, // *2
        splitOn: "*" ) // *3
        .AsList(); // *4
    

    *1 = > tells dapper that there will be two integers that will return a Tuple

    *2 = tells dapper to use a Tuple to return the result

    *3 = tells dapper that every field returned is used to return a result for each property of the Tuple.

    *4 = Dapper extension method to cast Dapper's internal result to a List; by default, Dapper returns a list under the covers so the cast will be faster than copying to a new list.

提交回复
热议问题