Have this scenario:
public class Base { public string Name; }
public Class ClassA :Base { public int32 Number; }
public Class ClassB :Base { public string Description;}
public Class DTO {
public string Name;
public int32 Number;
public string Description;
}
I have an IList<Base>
my maps are:
AutoMapper.Mapper.CreateMap<IList<Base>, IList<DTO>>()
.ForMember(dest => dest.Number, opt => opt.Ignore())
.ForMember(dest => dest.Description, opt => opt.Ignore());
AutoMapper.Mapper.CreateMap<ClassA, DTo>()
.ForMember(dest => dest.Description, opt => opt.Ignore());
AutoMapper.Mapper.CreateMap<ClassB, DTO>()
.ForMember(dest => dest.Number, opt => opt.Ignore())
Mapper.AssertConfigurationIsValid(); //Is OK!
But Properties that are in ClassA Or ClassB are not mapped when I do this :
IList<DTO>= AutoMapper.Mapper.Map<IList<Base>,IList<DTO>>(baseList);
How can I do to map properties that are defined in ClasA
and ClassB
At least with recent Automapper versions (>2.0?) your code is okay if you remove the
IList<>
:s of your firstCreateMap
statement1. And you don't have to create specific DTO classes as @Simon suggests in another answer (unless that's what you want).But to be specific about the inheritance and to avoid redundant mapping clauses when you extend the base class you can specify the inheritance by using the
.Include
method. So, if you create your mappings like this:then you can do this:
(Note that you don't have to map IList specifically. Automapper handles this for you.)
See this article about
.Include
.1Actually I wonder if the code compiled as written in the question?
I did this to solve the problem
Must be a better way to do this.
Following on from Eugene Gorbovoy's answer, if you're using profiles to configure your AutoMapper, you need to use a
TypeConverter
.Create a new
TypeConverter
like thisand replace the
ConvertUsing
line in his example withFor your scenario you have to use IMappingExpression.ConvertUsing method. By using it you can provide appropriate type for newly created object. Please, look at my example (pretty well fit your scenario):
You will need to create DTO classes that match your domain classes like this:
You then need to change your mappings to this:
Once this is done, then the following will work:
Unfortunately this does mean that you have an unwanted cast, but I don't think there's much that you can do about that.