使用Dapper进行多映射的摘要

时间:2019-07-10 15:01:27

标签: dapper

我想从数据库中获取其子对象的特定实现,但是显然没有这样做。

public class AbstractImplemenation 
{
    public Guid Id { get; set; }
}

public class SpecificImplemenation1 : AbstractImplemenation 
{
    public int Count { get; set; }
    public PStatus[] PStatuses { get; set; }
}

public class PStatus
{
    public Guid Id { get; set; }
    public PStatus PStatus { get; set; }
}

public async Task<AbstractImplemenation> GetImplementations(Guid id)
{
    var sql = "SELECT t.id, t.type tType, t.count, p.id pId, p.status pStatus FROM t " +
                "INNER JOIN s ON t.id=s.id " +
                "INNER JOIN p ON s.id=p.id " +
                "WHERE s.id=@id";

    using (var reader = await (await _db.GetConnection()).ExecuteReaderAsync(sql, new {id}))
    {
        var impl1 = reader.GetRowParser<AbstractImplemenation>(typeof(SpecificImplemenation1));

        var namedRowParsers = new Dictionary<string, Func<IDataReader, AbstractImplemenation>>
        {
            {"1", r => impl1(r)}
        };

        var typeColumnIndex = reader.GetOrdinal("tType");

        while (reader.Read())
        {
            var type = reader.GetString(typeColumnIndex);
            if (!namedRowParsers.ContainsKey(type))
            {
                throw new NotImplementedException();
            }

            return namedRowParsers[type](reader);
        }

        return null;
    }
}

0 个答案:

没有答案