我可以将结果映射到Dapper中的Tuple吗? [英] Can I map a result to Tuple in Dapper?

查看:284
本文介绍了我可以将结果映射到Dapper中的Tuple吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图选择2个整数列的列表,将结果映射到元组。例如:

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

return connection.Query<Tuple<int,int>>("select id1, id2 from sometable").ToList();

不起作用,但是如果我用两个整数创建一个类,例如:

does not work, but the same query does work if I create a class with two integers such as:

return connection.Query<BogusClass>("select id1, id2 from sometable").ToList();

public class BogusClass{
public int id1 {get;set;}
public int id2 {get;set;}
}

我的偏好是不必创建一些虚假的类来获取一些数据。在这种情况下,它是两个整数列,但我可以想到其他用例。

My preference is not to have to create some bogus class just to get some data to work with. In this case it is two integer columns, but there are other use cases I could think of.

编辑-答案:
这是适用的语法me HTH

Edit - Answer: This is the syntax that worked for me HTH

已更改:

return connection.Query<Tuple<int,int>>("select id1, id2 from sometable").ToList();

至:

return connection.Query<int, int, Tuple<int, int>>("select id1, id2 from sometable", Tuple.Create, splitOn: "*").ToList();


推荐答案

下面是一个有效的示例:

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

这篇关于我可以将结果映射到Dapper中的Tuple吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆