AutoMapper: mapping an object collection to a string collection

I need help with a custom mapping to AutoMapper. I want to match a collection of objects with a set of strings.

So I have a tagd class

public class Tag { public Guid Id { get; set; } public string Name {get; set; } } 

Than in the model I have an IList of this class. Now I want to match the name with a list of strings.

Here's how I define a matching rule:

 .ForMember(dest => dest.Tags, opt => opt.ResolveUsing<TagNameResolver>()) 

And here is my ValueResolver:

 protected override string ResolveCore(Tag source) { return source.Name; } 

But you know .. this does not work ;-) So maybe someone knows how to do it right and can help me.

thanks alot

Jan

Soooooooooooooooooooooooooooooooo and I wanted to get more detailed information.

So the model:

 public class Artocle { public Guid Id { get; set; } public string Title {get; set; } public string Text { get; set; } public IList<Tag> Tags { get; set; } } 

And the u tag model can see above.

I want to map it to ArticleView ... I need a tag model only for some business context, not for output.

So here is the ViewModel I need to map:

 public class ArticleView { public Guid Id { get; set; } public string Title { get; set; } public string Text { get; set; } public IList<string> Tags { get; set; } // The mapping problem :-) } 

So, I have a BootStrapper for mappings. My mapping is as follows:

 Mapper.CreateMap<Article, ArticleView>() .ForMember(dest => dest.Tags, opt => opt.ResolveUsing<TagNameResolver>()) 

And I match it manuelly with a special method

  public static ArticleView ConvertToArticleView(this Article article) { return Mapper.Map<Article, ArticleView>(article); } 
+6
source share
1 answer

A unit test confirmed the following: map from IList <Tag> to IList <string>

  private class TagNameResolver : ValueResolver<IList<Tag>, IList<string>> { protected override IList<string> ResolveCore(IList<Tag> source) { var tags = new List<string>(); foreach (var tag in source) { tags.Add(tag.Name); } return tags; } } 

This is a shorter way to create a map:

 .ForMember(dest => dest.Tags, opt => opt.MapFrom(so => so.Tags.Select(t=>t.Name).ToList())); 
+13
source

Source: https://habr.com/ru/post/893308/


All Articles