[英]Automapper doesn't map properly on hierarchy
I'm using Automapper to copy interfaces to different implementations (for serialization, for view model, for database mapping, etc...). 我正在使用Automapper将接口复制到不同的实现中(用于序列化,用于视图模型,用于数据库映射等)。
My code is a lot more complex but I've isolated the problem in the following code snippet sample. 我的代码复杂得多,但在下面的代码片段示例中隔离了该问题。
Considering the following code, do I miss something because the second assertion is failing : 考虑以下代码,由于第二个断言失败 ,我会错过什么吗:
[Test]
public void AutoMapperTest()
{
Mapper.CreateMap<IMyBaseInterface, MyClass>();
Mapper.CreateMap<IMyInterface, MyClass>();
IMyBaseInterface baseInstance = new MyBaseClass{ MyBaseProperty = "MyBase" };
var concrete = Mapper.Map<MyClass>(baseInstance);
concrete.MyClassProperty = "MyClass";
MyClass mapped = Mapper.Map<IMyInterface,MyClass>(concrete);
Assert.AreEqual(concrete.MyBaseProperty, mapped.MyBaseProperty);
Assert.AreEqual(concrete.MyClassProperty, mapped.MyClassProperty);
}
Expected: "MyClass" But was: null
预期:“ MyClass”但为:null
public class MyClass : MyBaseClass, IMyInterface
{
public string MyClassProperty { get; set; }
}
public interface IMyInterface : IMyBaseInterface
{
string MyClassProperty { get; }
}
public class MyBaseClass : IMyBaseInterface
{
public string MyBaseProperty { get; set; }
}
public interface IMyBaseInterface
{
string MyBaseProperty { get; }
}
Automapper : 4.1.1.0 / .Net: 4.5 / VS 2013 Automapper:4.1.1.0 / .NET 4.5 / VS 2013
Work around: Add Mapper.CreateMap<MyClass, MyClass>();
解决方法:添加
Mapper.CreateMap<MyClass, MyClass>();
I don't see the above as a real answer. 我不认为以上是真正的答案。 Since it means that if I have several implementations, I have to create mappings for all combinations.
因为这意味着如果我有多个实现,则必须为所有组合创建映射。 And add another mapping if I write a new implementation, even if the whole time, they all implement the same interface.
如果我编写一个新的实现,并添加另一个映射,即使它们始终都实现相同的接口。
If you are using inheritance and you want to combine this with Automapper
you have to say Automapper
that this class is base for these classes, and these classes are children of this class. 如果使用继承,并且要将其与
Automapper
结合使用,则必须说Automapper
该类是这些类的基础,并且这些类是该类的子类。 I had the same problem and it started work only when I specified ALL my inheritance relationships 我遇到了同样的问题,并且只有当我指定所有继承关系时,它才开始起作用
Its better to check this doc page about inheritance config 最好检查有关继承配置的此文档页面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.