使用Dapper在自定义Poco对象中返回模型

时间:2017-11-25 11:49:18

标签: c# mysql .net-core dapper

我使用以下查询聚合数据:

var result = Connection.Query<TransactionStatsByUserGrouped>(
    @"SELECT usr.*, st.Amount, st.Count
    FROM Users usr
    RIGHT JOIN (select UserId, sum(Amount) as Amount, sum(Count) Count
        FROM (
            SELECT User2Id as UserId, sum(Amount) as Amount, count(TransactionId) Count
            FROM Transactions
            WHERE User1Id = @UserId
            GROUP BY User2Id
    ) t GROUP BY UserId) st
    ON st.UserId = usr.UserId
    ORDER BY st.Amount DESC",
    param: new { UserId = userId },
    transaction: Transaction
);

自定义Poco对象具有以下结构:

public class TransactionStatsByUserGrouped
{
    public User User { get; set; }
    public decimal Amount { get; set; }
    public int Count { get; set; }
}

其中User是实际数据模型,包含以下属性:

public class User
{
    public string UserId { get; set; }
    public string Email { get; set; }
    public int Role { get; set; }
    public string Password { get; set; }
    // ...
}

我遇到的问题是我在null课程中获得了User模型的TransactionStatsByUserGrouped结果:

[
    {
        "user": null,
        "amount": 400.00,
        "count": 2
    },
    {
        "user": null,
        "amount": 100.00,
        "count": 1
    }
]

问题似乎在于,自定义TransactionStatsByUserGrouped类将模型用作属性,而不是将所有模型的属性列为TransactionStatsByUserGrouped类中的单独属性。有没有解决这个问题?我不想手动映射每个User模型属性。

我想在一个查询中返回用户的所有属性+每个属性的聚合统计信息。

.Net Core 2使用+ Dapper + MySQL个连接符(MariaDB

1 个答案:

答案 0 :(得分:1)

根据文档,您可以尝试Multi Mapping

var sql = 
  @"SELECT usr.*, st.Amount, st.Count
    FROM Users usr
    RIGHT JOIN (select UserId, sum(Amount) as Amount, sum(Count) Count
        FROM (
            SELECT User2Id as UserId, sum(Amount) as Amount, count(TransactionId) Count
            FROM Transactions
            WHERE User1Id = @UserId
            GROUP BY User2Id
    ) t GROUP BY UserId) st
    ON st.UserId = usr.UserId
    ORDER BY st.Amount DESC";

var result = Connection.Query<TransactionStatsByUserGrouped, User, TransactionStatsByUserGrouped>(
    sql,
    (group, user) => { group.User = user; return group;},
    param: new { UserId = userId },
    transaction: Transaction
);
相关问题