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

时间:2020-07-01 02:12:13

标签: c# asp.net-core .net-core automapper

我有一个Post and Tag类,在PostTag链接表中具有多对多关系。

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

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

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

这是我正在运行的查询,用于返回所有帖子:

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]]"
}

1 个答案:

答案 0 :(得分:2)

似乎可行,除了列表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);

在这里查看小提琴:https://dotnetfiddle.net/99fpwg