Reputation: 3424
I have complex data, that is returned from my API as follows:
"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": []
}
}
]
That corresponds to my Post.cs
entity, and I created new model class to map it with, which looks like this:
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; }
}
Where my Tag.cs
and TagModel.cs
classes lookk like this:
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; }
So, basically, I have a mapping as
CreateMap<Post, PostModel>()
.ReverseMap();
CreateMap<Tag, TagModel>()
.ReverseMap();
but what I get from the API once I do the mapping is this:
"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
So, as you can see the Tags
is not mapped. The reason is more likely that I have a many-to-many relationship between Post
and Tag
, and I originally get PostTags
from the API. How can I tell AutoMapper to map the tag
inside post_tags
to the corresponding tag inside PostModel
?
Upvotes: 1
Views: 590
Reputation: 1799
AutoMapper maps the collection, not the objects in that collection, individually. So, first ignore the collection and then handle it manually.
// 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]);
}
Upvotes: 2