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.

Andy
  • 8,432
  • 6
  • 38
  • 76

1 Answers1

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);
  • 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. – Andy May 10 '11 at 12:58
  • 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. – Andy May 10 '11 at 13:22
  • Thanks for your comments. I am sorry I couldn't be of any help! – Raffael Zaghet May 10 '11 at 17:28
  • No problem, I'm not sure why your example works, but other calls to Map don't! – Andy May 10 '11 at 19:34