Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 679
marcusstarnes Avatar asked Jun 25 '12 12:06

marcusstarnes


People also ask

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

Does AutoMapper map private properties?

AutoMapper will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .


2 Answers

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.

like image 142
Rob West Avatar answered Sep 26 '22 19:09

Rob West


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;     } } 
like image 27
ZafarYousafi Avatar answered Sep 26 '22 19:09

ZafarYousafi