Cant'似乎想出了这个。
public class DestinationClass
{
public int InnerPropertyId { get; set; }
public string StrignValue { get; set; }
}
public class SourceClass
{
public InnerValue Inner { get; set; }
}
public class InnerValue
{
public int InnerPropertyId { get; set; }
public string StrignValue {get;set;}
}
我需要从SourceClass.InnerValue直接映射到DestinationClass。我怎么做?
提前致谢。
答案 0 :(得分:10)
像往常一样,在我点击发布问题按钮后:
Mapper.Reset();
// from, to
Mapper.CreateMap<InnerValue, DestinationClass>();
Mapper.CreateMap<SourceClass, DestinationClass>()
.ConvertUsing(s => Mapper.Map<InnerValue, DestinationClass>(s.Inner));
Mapper.AssertConfigurationIsValid();
var source = new SourceClass() { Inner = new InnerValue() { InnerPropertyId = 123, StringValue = "somethinges" } };
var dest = Mapper.Map<SourceClass, DestinationClass>(source);
答案 1 :(得分:6)
我们确实遇到了ConvertUsing没有给出完全填充结果的问题,因为我们的SourceClass版本有一个我们想要映射到DestinationClass的附加值
我们确实发现以下代码给出了所需的结果:
{
...
Mapper.CreateMap<InnerValue, DestinationClass>(MemberList.Source);
Mapper.CreateMap<SourceClass, DestinationClass>(MemberList.Source)
.ConstructUsing(s => Mapper.Map<DestinationClass>(s.Inner))
.ForSourceMember(m => m.Inner, opt => opt.Ignore());
...
}
public class DestinationClass
{
public int InnerPropertyId { get; set; }
public string StringValue { get; set; }
public string SourceClassValue { get; set; }
}
public class SourceClass
{
public string SourceClassValue { get; set; }
public InnerValue Inner { get; set; }
}
public class InnerValue
{
public int InnerPropertyId { get; set; }
public string StrignValue {get;set;}
}
ConstructUsing在映射内部成员后继续映射其余成员,而ConvertUsing不映射。
答案 2 :(得分:5)
映射应如下所示:
CreateMap<SourceClass, DestinationClass>()
.ForMember(x => x.InnerPropertyId , x => x.MapFrom(z => z.Inner.InnerPropertyId))
.ForMember(x => x.StrignValue , x => x.MapFrom(z => z.Inner.StrignValue))
;