自动映射和类层次结构

时间:2011-05-09 20:29:57

标签: c# automapper derived

鉴于以下来源:

public class SourceBase { public string TheString { get; set; } }
public class SourceDerived : SourceBase { }

和目的地:

public class DestBase { public string MyString { get; set; } }
public class DestDerived : DestBase { }

这个映射:

  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

但是,这会给出一个映射错误,指出MyString未映射到DestDerived。是什么赋予了?我是否真的需要在所有派生类型中重复基类属性的映射(我的实际代码中确实有多个子类)。

编辑:

确切的异常是无法映射DestDerived的以下1个属性:MyString。在DestDerived 上添加自定义映射表达式,忽略或重命名该属性。

1 个答案:

答案 0 :(得分:0)

请查看此帖子: http://groups.google.com/group/automapper-users/browse_thread/thread/69ba514a521e9599

如果您在下面的代码中声明它(使用AutoMapper 1.1.0.188),它可以正常工作。我不确定这是否能解决你的问题。

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