Dapper - 将聚合函数分配给对象属性

时间:2017-11-16 16:21:54

标签: c# postgresql aggregate-functions dapper

我正在尝试将聚合函数(count(*))分配给查询中的dapper模型对象。这是我希望工作的代码,因为SQL肯定会:

public async Task<IEnumerable<ParentObj>> GetTopTrendingParentObjsAsync(
    DateTime? lowerBound = null, int count = TrendingCount)
{
    if (lowerBound == null) lowerBound = DateTime.UtcNow.AddDays(-1);

    var ParentObjs = new Dictionary<int, ParentObj>();
    Parent Obj
    await _connection.QueryAsync<ParentObj, ParentObjStatus, User, ParentObj>(@"
        SELECT s.*, COUNT(*) AS trend_rating, ss.*, author.id, author.username
        FROM ParentObj s
        INNER JOIN ParentObj_status ss
            ON ss.id = s.status_id
        INNER JOIN public.user author
            ON author.id = s.author_id
        LEFT JOIN user_ParentObj us
            ON us.ParentObj_id = s.id
                AND (us.create_date >= @lowerBound
                    AND us.status_id != @exited)
        WHERE s.status_id != ANY (@closedParentObjStatuses)                                      
        GROUP BY (s.id,ss.id,author.id)
        ORDER BY trend_rating DESC
        LIMIT (@count)
        ", (s, ss, author, us) =>
    {
        ParentObj ParentObj;

        if (!ParentObjs.TryGetValue(s.Id, out ParentObj))
        {
            ParentObjs.Add(s.Id, ParentObj = s);
            ParentObj.ParentObjStatus = ss;
            ParentObj.Author = author;
        }
        return ParentObj;
    }
    , new {
        count = count,
        lowerBound = lowerBound,
        closedParentObjStatuses = ParentObjStatus.ClosedStatuses,
        exited = UserParentObjStatusEnum.Exited
    }
    , splitOn: "id"
    );
    return ParentObjs.Values;
}

该模型有一个属性:

[Column("trend_rating")]
public virtual int? TrendRating { get; set; }

正确映射其余属性。检查C#对象时“TrendRating”的值始终为“1”,但在PgAdmin中手动执行的查询中,它具有正确的值:

enter image description here

这是通过在查询映射器中包含user_ParentObj表并为每行递增此属性来实现此目的的唯一方法吗?对我来说听起来像是INSANE。我知道我应该只是在一个视图或其他东西中这样做,但如果我不能让它为传统查询工作,为什么它会起作用呢?我想知道为什么命名列没有被映射,即使它不是表的一部分而且splitOn分隔符甚至在它之后等等。

我在这里缺少什么?

0 个答案:

没有答案