Suppose i have a source class:
public class Source
{
//Several properties that can be mapped to DerivedBase and its subclasses
}
And some destination classes:
public class DestinationBase
{
//Several properties
}
public class DestinationDerived1 : DestinationBase
{
//Several properties
}
public class DestinationDerived2 : DestinationBase
{
//Several properties
}
Then I wish the derived destination classes to inherit the automapper configuration of the baseclass because I do not want to have to repeat it, is there any way to achieve this?
Mapper.CreateMap<Source, DestinationBase>()
.ForMember(...)
// Many more specific configurations that should not have to be repeated for the derived classes
.ForMember(...);
Mapper.CreateMap<Source, DestinationDerived1 >()
.ForMember(...);
Mapper.CreateMap<Source, DestinationDerived2 >()
.ForMember(...);
When I write it like this it does not use the base mappings at all, and include doesn't seem to help me.
Edit: This is what I get:
public class Source
{
public string Test { get; set; }
public string Test2 { get; set; }
}
public class DestinationBase
{
public string Test3 { get; set; }
}
public class DestinationDerived1 : DestinationBase
{
public string Test4 { get; set; }
}
public class DestinationDerived2 : DestinationBase
{
public string Test5 { get; set; }
}
Mapper.CreateMap<Source, DestinationBase>()
.ForMember(d => d.Test3, e => e.MapFrom(s => s.Test))
.Include<Source, DestinationDerived1>()
.Include<Source, DestinationDerived2>();
Mapper.CreateMap<Source, DestinationDerived1>()
.ForMember(d => d.Test4, e => e.MapFrom(s => s.Test2));
Mapper.CreateMap<Source, DestinationDerived2>()
.ForMember(d => d.Test5, e => e.MapFrom(s => s.Test2));
AutoMapper.AutoMapperConfigurationException : Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
Source -> DestinationDerived1 (Destination member list)
Test3
Include derived mappings into base mapping:
Usage:
See Mapping inheritance on AutoMapper wiki.
UPDATE: Here is full code of classes which works as it should.
UPDATE (workaround of AutoMapper bug):
And all mappings:
NB! For those who are having issues with derived interfaces. AutoMapper does not support registering against derived interfaces. Only classes are handled.
To make it work, you have to change your type reference for CreateMap to the class instead of interface.
Example:
Any mapping against Interface2 will only use the first CreateMap. You will have to identify the second as
For Automapper 8.0.
Current version has new method IncludeAllDerived
Here's working example: