Domanda

By default in c# all classes inherit the ToString() method. The problem I'm having is that at work we are using the automapper to map some domain objects to the front end. I keep seeing code very similar to the following sudo.

string:mapToclass.name <- mapFromClass

the problem is that although i'm expecting a string to be mapped from i'm being sent a type with an automatic to string method. The correct code should be similar to the following.

string:mapToclass.name <- mapFromClass.name

Unfortunately because of the automatic inheritance of the ToString method both of these will compile and run. I've though of possibly overriding the string to throw a not implemented exception, but it's not a good design and breaks lsp, plus it still wouldn't catch the error at compile time which would be more ideal.

Any ideas how I could possibly enforce this?

È stato utile?

Soluzione

If I'm reading this correctly then you can manually specify a mapping in AutoMapper for a case like this.

Mapper.CreateMap<MapFromClass, MapToClass>().ForMember(dest => dest.name, opt => opt.MapFrom(src => src.name));

This will explicitly map from a property on the MapFromClass to the MapToClass. More information on this question.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top