Can I map a result to Tuple in Dapper?

萝らか妹 提交于 2019-12-01 02:09:00

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));
    }
}

You can find more examples here.

You can like so

string query = "Select value1 as Item1,value2 as Item2 from #sometable";
var data = db.Query<Tuple<int,int>>(query);

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.

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<dynamic>(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<Tuple<int, int>> result = conn.Query<int, int, Tuple<int, int>>( // *1
    sql,
    Tuple.Create, // *2
    splitOn: "*" ) // *3
    .AsList(); // *4

*1 = <int,int, Tuple<int, int>> 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.

For those using async, this can be achieved by using ValueTuple.

var res = await conn.QueryAsync<(int Id1, int Id2)>(sql);

List<Tuple<int, int>> tuples = res.Select(x => new Tuple<int, int>(x.Id1, x.Id2)).ToList();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!