【问题标题】:Returning model in a custom Poco object using Dapper使用 Dapper 在自定义 Poco 对象中返回模型
【发布时间】:2018-05-09 04:45:06
【问题描述】:

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

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; }
    // ...
}

我遇到的问题是我在TransactionStatsByUserGrouped 类中得到null 模型的null 结果:

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

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

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

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

【问题讨论】:

标签: c# mysql .net-core dapper


【解决方案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
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2013-06-09
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多