首页 > 解决方案 > 具有 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
}
]

标签: c#jsonpostgresqlasp.net-coredapper

解决方案


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;";

推荐阅读