我使用以下查询聚合数据:
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
)
答案 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
);