问题
I'm trying to use AutoMapper (v5.1.1) to map an object which inherits from a List or Collection. The map call does not give me an error but the output is an empty list (of correct type though).
I can get a List<DestinationObject>
or Collection<DestinationObject>
, but it does not seem to work when having a custom class which enherits from List<T>
or Collection<T>
.
I've tried extending the first map definition to include the base class (List<T>
) but that gives me a StackOverflowException.
cfg.CreateMap(typeof(SourceCollection), typeof(DestinationCollection)).Include(typeof(List<SourceObject>), typeof(List<DestinationObject>));
What am I missing here?
public class SourceCollection : List<SourceObject> {
}
public class DestinationCollection : List<DestinationObject> {
}
public class SourceObject {
public string Message { get; set; }
}
public class DestinationObject {
public string Message { get; set; }
}
static void Main(string[] args)
{
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap(typeof(SourceCollection), typeof(DestinationCollection));
cfg.CreateMap<List<SourceObject>, List<DestinationObject>>().Include<SourceCollection, DestinationCollection>();
cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject));
});
AutoMapper.Mapper.AssertConfigurationIsValid();
SourceCollection srcCol = new SourceCollection() { new SourceObject() { Message = "1" }, new SourceObject() { Message = "2" } };
DestinationCollection dstCol = AutoMapper.Mapper.Map<SourceCollection, DestinationCollection>(srcCol);
}
回答1:
You just have to map sourceobject to destinationobject, AutoMapper will do rest of the magic, More on this can be found on this link
cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject));
来源:https://stackoverflow.com/questions/39971563/automapper-and-inheritance-from-collection-or-list