使用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
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因