Using AutoMapper to map the property of an object to a string

后端 未结 2 831
野性不改
野性不改 2020-12-05 12:53

I have the following model:

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

I want to be able to

相关标签:
2条回答
  • 2020-12-05 13:44

    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.

    0 讨论(0)
  • 2020-12-05 13:46

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题