Automapper and class hierarchy
Asked Answered
R

1

6

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 mapping error saying MyString isn't mapped on DestDerived. What gives? Do I really need to repeat the mappings for base class properties in all derived types (I do have more than one subclass in my actual code).

EDIT:

The exact exception is The following 1 properties on DestDerived could not be mapped: MyString. Add a custom mapping expression, ignore, or rename the property on DestDerived.

Relations answered 9/5, 2011 at 20:29 Comment(1)
What is the exact error?Esculent
T
0

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

It works fine if you declare it like 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);
Tore answered 9/5, 2011 at 21:53 Comment(4)
No this doesn't work for us. Its really odd too that if you call Mapper.Map(source, typeof(SourceDerived), typeof(DestDerived)) then your sample code fails. No exception, but no mapping is done either.Relations
We are also calling Mapper.AssertConfigurationIsValid(). I think you'll find that if you add that call right after you setup your mappings, you'll get the exception mentioned in my post.Relations
Thanks for your comments. I am sorry I couldn't be of any help!Tore
No problem, I'm not sure why your example works, but other calls to Map don't!Relations

© 2022 - 2024 — McMap. All rights reserved.