繁体   English   中英

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

[英]AutoMapper and manually mapping nested complex types

我有复杂的数据,这些数据是从我的API返回的,如下所示:

"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.csTagModel.cs类看起来像这样:

Tag.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>();
}

TagModel.cs:

public int Id { get; set; }

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

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

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

但是一旦完成映射,我从API中得到的是:

"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

因此,如您所见, Tags未映射。 原因很可能是PostTag之间存在多对多关系,并且最初PostTags从API获取PostTags的。 如何告诉AutoMapper将post_tagstag post_tagsPostModel的相应标签?

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

暂无
暂无

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

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