2

这里是 Dapper 的新手!多映射有问题。这是我的查询:

var sql = @"select distinct a.*, 
                c.Id as 'GenreId', c.Active as 'GenreActive', c.Link as 'GenreLink', c.Name as 'GenreName', c.DateCreated as 'GenreDateCreated', c.DateEdited as 'GenreDateEdited',
                d.Id as 'CommentId', d.ReviewId as 'CommentReviewId', d.Name as 'CommentName', d.Email as 'Comment.Email', d.Content as 'CommentContent', d.Active as 'CommentActive', d.DateCreated as 'CommentDateCreated', d.DateEdited as 'CommentDateEdited', d.CommentId as 'ReplyCommentId' 
                from Review a " +
               "left join ReviewGenre b on a.Id = b.ReviewId " +
               "left join Genre c on c.Id = b.ReviewId " +
               "left join Comment d on a.Id = d.ReviewId " +
               "where a.Active = 1 " +
               "order by a.DatePublished desc;"
            ;

我的实体是(为简洁起见缩短):

public class Review 
{
    public int Id {get;set;}
    public IEnumerable<Genre> Genres { get; set; }
    public IEnumerable<Comment> Comments { get; set; }
}

public class Genre 
{
    public int Id {get;set;}
    public string Name {get;set;}
}

public class Comment 
{
    public int Id {get;set;}
    public int Content {get;set;
}

我使用 Dapper 的查询尝试拆分 Genre.Id 和 Comment.Id 的重命名列。该查询似乎工作正常,但没有任何流派和评论似乎映射到 Review 类。这就是我尝试执行查询的方式:

 using (var connection = new SqlConnection(_ConnectionString))
            {
                var reviews = await connection.QueryAsync<Review, Genre, Comment, Review>(
                    sql,
                    (review, genre, comment) =>
                    {
                        review.Genres = new List<Genre>();
                        review.Comments = new List<Comment>();

                        if (genre != null)
                        {
                            review.Genres.ToList().Add(genre);
                        }

                        if (comment != null)
                        {
                            review.Comments.ToList().Add(comment);
                        }

                        return review;
                    },
                    commandType: CommandType.Text,
                    splitOn: "GenreId,CommentId");

                return reviews;
            }

我已经研究了整个教程和关于该主题的 SO,但没有找到可能导致映射不发生的原因。

我会很感激任何建议(Dapper 的新手)。谢谢!

4

1 回答 1

2

在这一行

review.Genres.ToList().Add(genre);

您每次都在创建一个新列表 ( .ToList())。此方法返回/创建新实例,但从未将新实例分配回模型属性。这就像做这样的事情:

var list = new List<int>();
new List<int>().Add(1);

这两个实例是单独的对象。

您可以做的是将模型更改为像这样工作(列表是通过创建对象来实例化的):

public class Review 
{
    public int Id {get;set;}
    public List<Genre> Genres { get; set; } = new List<Genre>();
    public List<Comment> Comments { get; set; } = new List<Comment>();
}

然后添加这样的元素:

review.Genres.Add(genre);

或者您可以查看原始的 dapper 教程,他们使用字典作为状态管理器来删除重复项。

于 2019-10-27T17:55:40.080 回答