Automation and class hierarchy

Given the following sources:

public class SourceBase { public string TheString { get; set; } } public class SourceDerived : SourceBase { } 

and destinations:

 public class DestBase { public string MyString { get; set; } } public class DestDerived : DestBase { } 

And this mapping:

  CreateMap<SourceBase, DestBase>() .ForMember(dest => dest.MyString, o => o.MapFrom(x => x.TheString)) .Include<SourceDerived, DestDerived>(); CreateMap<SourceDerived, DestDerived>(); Mapper.AssertConfigurationIsValid(); // Exception is thrown here 

However, this gives a display error in which MyString is not displayed in DestDerived. What gives? Do I really need to repeat the mappings for the properties of the base class in all derived types (I have several subclasses in my actual code).

EDIT:

Exact exception. The following 1 properties in DestDerived cannot be mapped: MyString. Add your own display expression, ignore or rename the property to DestDerived.

+6
source share
1 answer

Please check this post: http://groups.google.com/group/automapper-users/browse_thread/thread/69ba514a521e9599

It works great if you declare it as in the code below (using AutoMapper 1.1.0.188). I am not sure if this solves your problem.

 var result = Mapper.CreateMap<SourceBase, DestBase>() .ForMember(dest => dest.MyString, o => o.MapFrom(x => x.TheString)); //.Include<SourceDerived, DestDerived>(); Mapper.CreateMap<SourceDerived, DestDerived>(); var source = new SourceDerived(); var destDerived = new DestDerived(); source.TheString = "teststring"; var mapResult = Mapper.Map<SourceBase, DestBase>(source, destDerived).MyString; Console.WriteLine(mapResult); 
0
source

Source: https://habr.com/ru/post/887658/


All Articles