开发者

Automapper and class hierarchy

开发者 https://www.devze.com 2023-03-04 06:16 出处:网络
Given the following sources: public class SourceBase { public string TheString { get; set; } } public class SourceDerived : SourceBase { }

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 prope开发者_StackOverflow中文版rties 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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消