AutoMapper和手动映射嵌套的复杂类型

时间:2018-05-25 20:06:23

标签: c# automapper

我有复杂的数据,从我的API返回如下:

flatMapping

这对应于我的"id": 1002, "user_id": "98fd8f37-383d-4fe7-9b88-18cc8a8cd9bf", "organization_id": null, "content": "A post with a hashtag!", "created_at": "2018-05-25T21:35:31.5218467", "modified_at": "2018-05-25T21:35:31.5218467", "can_comment": true, "can_share": true, "post_tags": [ { "post_id": 1002, "tag_id": 1, "tag": { "id": 1, "value": "hashtag", "post_tags": [] } } ] 实体,我创建了新的模型类来映射它,如下所示:

Post.cs

我的public class PostModel { public int Id { get; set; } [Required] public string UserId { get; set; } public int? OrganizationId { get; set; } [Required] public string Content { get; set; } public DateTime CreatedAt { get; set; } public DateTime ModifiedAt { get; set; } public bool CanComment { get; set; } = true; public bool CanShare { get; set; } = true; public List<Tag> Tags { get; set; } } Tag.cs类看起来像这样:

Tag.cs​​:

TagModel.cs

TagModel.cs:

public class Tag
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Value { get; set; }

    public ICollection<PostTag> PostTags { get; set; } = new List<PostTag>();
}

所以,基本上,我有一个映射为

public int Id { get; set; }

[Required]
public string Value { get; set; }

但是,一旦我进行映射,我从API获得的是:

CreateMap<Post, PostModel>()
    .ReverseMap();
CreateMap<Tag, TagModel>()
    .ReverseMap();

因此,您可以看到"id": 1002, "user_id": "98fd8f37-383d-4fe7-9b88-18cc8a8cd9bf", "organization_id": null, "content": "Finally a post with a hashtag!", "created_at": "2018-05-25T21:35:31.5218467", "modified_at": "2018-05-25T21:35:31.5218467", "can_comment": true, "can_share": true, "tags": null 未映射。原因更可能是TagsPost之间存在多对多关系,而我最初从API获得Tag。如何告诉AutoMapper将PostTags内的tag映射到post_tags内的相应标记?

1 个答案:

答案 0 :(得分:2)

AutoMapper分别映射集合,而不是该集合中的对象。因此,首先忽略该集合,然后手动处理它。

// Map the Post and ignore the Tags
AutoMapper.Mapper.CreateMap<Post, PostModel>()
.ForMember(dest => dest.Tags,
           opts => opts.Ignore());

// Map the Tags and ignore the post_tags
AutoMapper.Mapper.CreateMap<Tag, TagModel>()
.ForMember(dest => dest.post_tags,
           opts => opts.Ignore());

// Map the Post Model
AutoMapper.Mapper.Map(post, postModel);

// Map the tags
for (int i = 0; i < post.post_tags.Count(); i++)
{
    AutoMapper.Mapper.Map(post.post_tags[i], postModel.Tags[i]);
}