开发者

AutoMapper: Mapping a collection of Object to a collection of strings

开发者 https://www.devze.com 2023-03-21 22:01 出处:网络
I need help with a special mapping with AutoMapper. I want to map a collection of objects to a collection of strings.

I need help with a special mapping with AutoMapper. I want to map a collection of objects to a collection of strings.

So I have a Tag class

public class Tag
{
    public Guid Id { get; set; }
    public string Name {get; set; }
}开发者_如何学编程

Than in a model I have a IList of this class. Now I want to map the name's to a collection of strings.

Thats how I define the mapping 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.. it doesn't work ;-) So maybe someone know how to do it right and can help me.

thanks a lot

Update to Jan

Sooo.. you wanted more details.. here you got it.. but I have shorten it ;)

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 Tag model you can see above.

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

So here is the ViewModel I need to map to:

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 the mappings. My Mapping looks like this:

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

And I map it manuelly with a special method

    public static ArticleView ConvertToArticleView(this Article article)
    {
        return Mapper.Map<Article, ArticleView>(article);
    }


A unit test validated the following would 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 of creating the map:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号