繁体   English   中英

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

[英]AutoMapper Error mapping types when mapping navigation property

我有一个 Post 和 Tag class,在 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]]"
}

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

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

rest 看起来不错,以下对我有用:

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

请参阅此处的小提琴: https://dotnetfiddle.net/99fpwg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM