Using AutoMapper to map the property of an object to a string
Asked Answered
H

2

44

I have the following model:

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

I want to be able to use AutoMapper to map the Name property of the Tag type to a string property in one of my viewmodels.

I have created a custom resolver to try to handle this mapping, using the following code:

public class TagToStringResolver : ValueResolver<Tag, string>
    {
        protected override string ResolveCore(Tag source)
        {
            return source.Name ?? string.Empty;
        }
    }

I am mapping using the following code:

Mapper.CreateMap<Tag, String>()
    .ForMember(d => d, o => o.ResolveUsing<TagToStringResolver>());

When I run the application I get the error:

Custom configuration for members is only supported for top-level individual members on a type.

What am I doing wrong?

Hanforrd answered 25/6, 2012 at 12:51 Comment(0)
C
62

This is because you are trying to map to the actual destination type rather than a property of the destination type. You can achieve what you want with:

Mapper.CreateMap<Tag, string>().ConvertUsing(source => source.Name ?? string.Empty);

although it would be a lot simpler just to override ToString on the Tag class.

Chanel answered 25/6, 2012 at 14:37 Comment(2)
Thanks Rob. I ended up going with your suggestion to simply override ToString on the Tag class.Hanforrd
Thanks for this. Out of naivety I was using ForMember() when I should have been using ConvertUsing().Elapse
L
16

ForMember means you are providing mapping for a member where you want a mapping between type. Instead, use this :

Mapper.CreateMap<Tag, String>().ConvertUsing<TagToStringConverter>();

And Converter is

public class TagToStringConverter : ITypeConverter<Tag, String>
{
    public string Convert(ResolutionContext context)
    {
        return (context.SourceValue as Tag).Name ?? string.Empty;
    }
}
Lehmann answered 25/6, 2012 at 14:36 Comment(1)
This helped me to map a whole entity. I had to map a ViewModel to a Entity, and this was the way to go, thanks!Geezer

© 2022 - 2024 — McMap. All rights reserved.