将具有表示列表的字符串的列映射到List<>使用Dapper的对象

时间:2016-01-21 16:33:45

标签: sql-server dapper string-split dapper-extensions

我有以下型号:

public class Model {
   public string Name { get; set; }
   public List<int> Numbers { get; set; }
}

返回包含两个nvarchar列的以下数据集的SQL查询:

 Name |  Numbers
'foo' | '1,2,3,4'
'bar' | '4,17'

是否有一种使用List<Model>将查询结果自动分配给Dapper的简单方法?

我知道我可以使用多映射并在C#代码中自行拆分,但我宁愿得到一个更简单的解决方案。

2 个答案:

答案 0 :(得分:2)

我不确定你是否可以称之为“更简单”,但这样的话是一个选择:

public class Result
{
    public string Name { get; set; }
    public List<int> Numbers { get; set; }
}
public class DapperTests
{
    [Test]
    public void Test()
    {
        var conn = new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=mydb");

        conn.Open();

        var result = conn.Query<string, string, Result>(
                    "select Name = 'Foo', Numbers = '1,2,3' union all select Name = 'Bar', Numbers = '4,5,6'", (a, b) => new Result
                    {
                        Name = a,
                        Numbers = b.Split(',').Select(Int32.Parse).ToList()
                    }, splitOn: "*").ToList();

        Assert.That(result.Count, Is.EqualTo(2));
        Assert.That(result.FirstOrDefault(x => x.Name == "Foo").Numbers.Count, Is.GreaterThan(0));
        Assert.That(result.FirstOrDefault(x => x.Name == "Bar").Numbers.Count, Is.GreaterThan(0));
    }
}

答案 1 :(得分:2)

多重映射的替代选项......非常难看

public class Result
{
    public string Name { get; set; }
    public List<int> NumberList { get; set; }
    public string Numbers { set { NumberList = value.Split(',').Select(Int32.Parse).ToList(); } }
}

public class DapperTests
{
    [Test]
    public void Test()
    {
        var conn = new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=mydb");

        conn.Open();

        var sql = @"
            select Name = 'Foo', Numbers = '1,2,3';
            select Name = 'Bar', Numbers = '4,5,6';";

        var expectedResults = 2;

        var results = new List<Result>();
        using (var multi = conn.QueryMultiple(sql))
        {
            for (int i = 0; i < expectedResults; i++)
            {
                results.Add(multi.Read<Result>().Single());
            }
        }

        Assert.That(results.Count, Is.EqualTo(2));

        Assert.That(results.FirstOrDefault(x => x.Name == "Foo").NumberList.Count, Is.GreaterThan(0));
        Assert.That(results.FirstOrDefault(x => x.Name == "Bar").NumberList.Count, Is.GreaterThan(0));
    }
}