映射导航时 AutoMapper 错误映射类型 属性

AutoMapper Error mapping types when mapping navigation property

我有一个 Post 和标签 class,在 Post 标签 link table 中有一个多对多关系。

public class Post
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTag { get; set; }

    public string AppUserId { get; set; }
    public AppUser AppUser { get; set; }
}

public class Tag
{
    public Guid Id { get; set; }
    public string Name { get; set;  }
    public List<PostTag> PostTag { get; set; }
}

public class PostTag
{
    public Guid PostId { get; set; }
    public Post Post { get; set; }

    public Guid TagId { get; set; }
    public Tag Tag { get; set; }
}

我正在尝试使用 AutoMapper 创建自定义映射,PostDto,如下所示:

public class PostDto
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    [JsonProperty("tags")]
    public List<TagDto> PostTags { get; set; }

    public UserDto User { get; set; }
}

public class TagDto
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class UserDto
{
    public string DisplayName { get; set; }
}

这是我 运行 return 所有 Post 的查询:

var posts = await _ctx.Posts
                        .Include(s => s.PostTags)
                        .ThenInclude(st => st.Tag)
                        .ToListAsync();

return _mapper.Map<List<Post>, List<>>(posts); // _mapper is injected using IMapper

映射配置文件:

CreateMap<UserDto, AppUser>()
    .ForMember(d => d.DisplayName, o => o.MapFrom(s => s.DisplayName));

CreateMap<Post, PostDto>();
    .ForMember(d=> d.User, o=>o.MapFrom(s => s.Appuser))
    .ForMember(d=> d.PostTags, o=>o.MapFrom(s=>s.PostTag));

CreateMap<PostTag, TagDto>()
    .ForMember(d => d.Id, o => o.MapFrom(s => s.Tag.Id))
    .ForMember(d => d.Name, o => o.MapFrom(s => s.Tag.Name));

导致此错误:

{
errors: "Error mapping types. Mapping types: List`1 -> List`1 System.Collections.Generic.List`1[[Domain.Post, Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[Application.PostDto, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"
}

似乎有效,除了列表 Post.PostTag 映射到 DTO 中名称略有不同的内容:PostDto.PostTags,需要映射器配置文件中的成员规则:

CreateMap<Post, PostDto>()
    .ForMember(d=> d.PostTags, o=>o.MapFrom(s=>s.PostTag));

其余的看起来还不错,下面的对我来说很有效:

List<Post> posts = ...blah
var dtos = mapper.Map<List<PostDto>>(posts);

请参阅此处 fiddle:https://dotnetfiddle.net/99fpwg