0

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?

crthompson
  • 15,653
  • 6
  • 58
  • 80
Lee
  • 564
  • 7
  • 16
  • You need to either override `ToString` yourself on the classes you need to, or find the code that takes the values and change how it works. – gunr2171 Sep 05 '13 at 16:30
  • Plus, there is no way to create a `Syntax Error` unless you make your own compiler. You mean a runtime exception. – gunr2171 Sep 05 '13 at 16:32
  • You can add code rules that create a sudo-syntax error, we are already doing it here but i'm not sure how i'd implement it in this case. – Lee Sep 05 '13 at 16:38
  • How are you enforcing the rules? If the problem is how to write a rule that can catch this behavior, then add some details about it. – gunr2171 Sep 05 '13 at 16:41
  • Can you add the actual code that goes behind this? I just attempted to recreate this and Automapper correctly maps mapFromClass.name to mapToClass.name for me. https://gist.github.com/DustinVenegas/6460252 – Dustin Venegas Sep 06 '13 at 06:32

1 Answers1

0

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.

Community
  • 1
  • 1
Dustin Venegas
  • 760
  • 1
  • 7
  • 16
  • Yes this is currently how it supposed to work, but this will also compile. Mapper.CreateMap().ForMember(dest => dest.name, opt => opt.MapFrom(src => src)); because everything has a default to string method. – Lee Sep 05 '13 at 23:30
  • Ahh, I see what you're saying now. I can't test this currently but you might try Mapper.AssertConfigurationIsValid();. According to the docs at https://github.com/AutoMapper/AutoMapper/wiki/Configuration-validation AutoMapper checks to make sure that every single Destination type member has a corresponding type member on the source type. – Dustin Venegas Sep 06 '13 at 06:21