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

dapper dapper-extensions sql-server string-split

我有以下型号:

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'

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

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

一般承认的答案

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

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

热门答案

多重映射的另一种选择......非常难看

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


许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow