Dapper: Multi-Mapping with repeating column names

2020-03-30 09:37发布

问题:

I have a table that looks like this:

ID   ERR1 ERR2 ERR3
---- ---- ---- ----
05A2 A001 B223 C212
06B3 B392 C234 D234
...

I would like to map it to objects that look like this:

public class Entry
{
    public string Id { get; set; }
    public List<BpcError> Errors { get; set; }

    public Entry()
    {
        Errors = new List<BpcError>();
    }
}

public class BpcError
{
    public string ErrorCode { get; set; }
    // More properties and methods to follow
}

How can I do this?

回答1:

Here's how:

string sql = "SELECT ID, "
    + "ERR1 AS ErrorCode, "
    + "ERR2 AS ErrorCode, "
    + "ERR3 AS ErrorCode "
    + "FROM ERR_TB";

List<Entry> entries = connection.Query<Entry, BpcError, BpcError, BpcError, Entry>(sql,
(entry, e1, e2, e3) =>
{
    if (e1 != null)
        entry.Errors.Add(e1);

    if (e2 != null)
        entry.Errors.Add(e2);

    if (e3 != null)
        entry.Errors.Add(e3);

    return entry;
},
splitOn: "ErrorCode, ErrorCode, ErrorCode")
.ToList();


标签: c# dapper