我正在尝试映射两个继承不同基(但具有公共属性)的类。当我使用Map时,父属性不会自动映射(我认为这应该基于固有定律)。如果我错了,请建议:
public class SourceBase
{
public bool IsSuccess { get; set; }
}
public class DestBase
{
public bool Success { get; set; }
}
public class ChildSource : SourceBase
{
public string SourceName { get; set; }
}
public class ChildDest : DestBase
{
public string DestName { get; set; }
}
创建地图
AutoMapper.Mapper.CreateMap<SourceBase, DestBase>()
.ForMember(dest => dest.Success, opt => opt.MapFrom(source => source.IsSuccess));
AutoMapper.Mapper.CreateMap<ChildSource, ChildDest>()
.ForMember(dest => dest.DestName,opt=>opt.MapFrom(source=>source.SourceName));
使用地图
ChildSource ch = new ChildSource()
{
IsSuccess = true,
SourceName = "user1"
};
var obj = AutoMapper.Mapper.Map<ChildDest>(ch);
我期望IsSuccess为True,DestName为user1。但是只有SourceName被设置,并且IsSuccess保持为false。若我在两者中使用相同的名称(IsSuccess),它会起作用,这是因为通过名称自动映射。但是如何在不同的类中使用不同属性名称(但类型相同)的现有格式。在为每个子类编写映射时,我不想显式映射父属性。
您需要使用Include方法告诉AutoMapper有关继承的信息:
Mapper.CreateMap<SourceBase, DestBase>()
.Include<ChildSource, ChildDest>()
.ForMember(dest => dest.Success, opt => opt.MapFrom(source => source.IsSuccess));