c# - 具有 COUNT 的 Dapper 嵌套对象始终返回 0
问题描述
我正在尝试使用 Dapper 和 postgres 执行以下操作。
我得到了所有的图像,每个模型的评论都嵌套在里面,但投票总数始终为 0。我认为这是 Dapper 中的映射,就好像我在 PGAdmin 中手动运行 SQL 一样,它会正确返回。
该模型:
public class Image
{
public int Id { get; set; }
public string Url { get; set; }
public DateTime DateTaken { get; set; }
public virtual List<Comment> Comments { get; set; }
public int VoteTotal { get; set; }
}
我的回购代码:
string sql = $"SELECT i.*, c.*, count(v.id) as votetotal " +
$"FROM image i " +
$"INNER JOIN comment c ON i.id = c.imageid " +
$"INNER JOIN vote v ON i.id = v.imageid " +
$"group by i.id, c.id;";
var lookup = new Dictionary<int, Image>();
connection.Query<Image, Comment, Image>(sql, (i, c) =>
{
if (!lookup.TryGetValue(i.Id, out Image image))
{
lookup.Add(i.Id, image = i);
}
if (image.Comments == null) image.Comments = new List<Comment>();
image.Comments.Add(c);
return image;
}).AsQueryable();
json:
[
{
"id": 1,
"url": "google.com/animage",
"dateTaken": "2000-01-01T00:00:00",
"comments": [
{
"id": 5,
"imageId": 1,
"commentText": "two comment",
"createdBy": "Sam",
"createdOn": "2021-03-05T13:39:21.065"
},
{
"id": 4,
"imageId": 1,
"commentText": "one comment",
"createdBy": "Pam",
"createdOn": "2021-03-05T13:39:21.065"
}
],
"voteTotal": 0
}
]
解决方案
VoteTotal 应该进入第一个映射,因为你在 Image 中有。当 Comment 已经被映射时,它是 SQL 中的最后一个,所以它不会被映射。您应该将 SQL 更改为:
string sql = @"SELECT count(v.id) as votetotal, i.*, c.*
FROM image i INNER JOIN comment c ON i.id = c.imageid
INNER JOIN vote v ON i.id = v.imageid
GROUP BY i.id, c.id;";
推荐阅读
- swift - 如何将字符串传递给子视图?
- httprequest - 错误 429 TooManyRequests 的冷却时间有多长?
- css - 除了 SCSS 文件,我如何让 Next 处理常规 CSS 文件?
- angular - 通过参数调用api输入的角度问题
- excel - 从关闭窗口激活工作表按预期工作,但不是从加载项菜单栏中的退出选项
- spring-kafka - Spring Kafka Unit Tests 触发监听,但是方法使用consumer.poll无法获取消息
- linux - 定义 libgcc_s.so.1 的位置
- c++ - 使用不同的链接器会产生不同的机器代码吗?
- python - 在 pandas 中,如何将数字类型转换为类别类型以与 seaborn hue 一起使用
- reactjs - 使用 Jest 和 React Native 测试库对 DateTimePickerModal 进行问题测试