我有以下课程:
public class TestClass
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ParentSource
{
public int A { get; set; }
public List<TestClass> LstSource { get; set; }
}
public class ChildSource : ParentSource
{
public int B { get; set; }
}
public class ParentDestination
{
public int A { get; set; }
public List<TestClass> LstDestination { get; set; }
}
public class ChildDestination : ParentDestination
{
public int B { get; set; }
}
我正在尝试使用AutoMapper版本1.1.0.188将ChildSource映射到ChildDestination。
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ParentSource, ParentDestination>()
.Include<ChildSource, ChildDestination>()
.ForMember(dest => dest.LstDestination, opt => opt.MapFrom(src => src.LstSource))
.ForMember(dest => dest.A, opt => opt.MapFrom(src => src.A));
cfg.CreateMap<ChildSource, ChildDestination>()
.ForMember(dest => dest.B, opt => opt.MapFrom(src => src.B));
});
然后我做了一个测试:
ChildSource test = new ChildSource();
test.LstSource = new List<SourceTestClass>() { new SourceTestClass() { ID = 3, Name = "abc" }, new SourceTestClass() { ID = 11, Name = "xyz" } };
test.A = 100;
test.B = 200;
ChildDestination result = Mapper.Map<ChildSource, ChildDestination>(test);
对象结果包含正确的A和B值,但LstSource null 。我做错了什么?
答案 0 :(得分:0)
我在这里回答了这个Automapper inheritance -- reusing maps
...剪断
你不能这样做我不认为 - 你需要将映射放在一起。这实际上可能是一个错误,因为维基声称它可以完成 - 但是给出的示例只是依靠属性的名称来进行映射,而不是包含位。至少这是我理解它的方式。
如果您查看http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays并更改Source和Dest中的属性名称(我将它们设置为Value 3和Value4以实际混合),那么明确地添加您的映射。
Mapper.CreateMap<ChildSource, ChildDestination>()
.ForMember( x => x.Value4, o => o.MapFrom( y => y.Value2 ) );
Mapper.CreateMap<ParentSource, ParentDestination>()
.Include<ChildSource, ChildDestination>()
.ForMember( x => x.Value3, o => o.MapFrom( y => y.Value1 ) );
然后它似乎失败了。
ChildSource s = new ChildSource()
{
Value2 = 1,
Value1 = 3
};
var c = s.MapTo<ChildDestination>();
var c2 = s.MapTo<ParentDestination>();
Assert.AreEqual( c.Value3, s.Value1 );
Assert.AreEqual( c.Value4, s.Value2 );
Assert.AreEqual( c2.Value3, s.Value1 );
Assert.AreEqual( c.Value4, s.Value2 );
其他笔记
此外,Include需要是孩子而不是父母。原型实际上说明了这个
public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination
根据我的阅读,您应首先创建您的子映射,尽管这可能是一个老问题。
Mapper.CreateMap<ChildSource, ChildDest>();
然后你的父母
Mapper.CreateMap<ParentSource, Parent Dest>()
.Include<ChildSource, ChildDest>();
来自http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays