我正在尝试将我的 DTO 对象映射到我的工厂类中的实体对象。DTO 具有所有字段值,而实体具有由名称和值组成的字段。
经过一番调试,我发现 Automapper 实例化了每个实体字段,而不是使用现有的。结果,最后一次测试失败。
[TestFixture]
class RecursiveMappingTest
{
public class SourceInfo
{
public string Info1 = "info1";
public string Info2 = "info1";
}
public class StringField
{
public string Name;
public string Value;
}
public class DestinationInfo
{
public StringField Info1 = new StringField() { Name = "field name 1" };
public StringField Info2 = new StringField() { Name = "field name 2" };
}
[Test]
public void MapField()
{
Mapper.CreateMap<string, StringField>()
.ForMember(dest => dest.Value, opt => opt.MapFrom(src => src));
Mapper.CreateMap<SourceInfo, DestinationInfo>();
SourceInfo sourceInfo = new SourceInfo();
DestinationInfo destinationInfo = new DestinationInfo();
Mapper.Map(sourceInfo, destinationInfo);
// these pass
Assert.That(destinationInfo.Info1.Value, Is.EqualTo("info1"));
Assert.That(destinationInfo.Info2.Value, Is.EqualTo("info1"));
// this fails since automapper instantiated brand new StringField()
// which has Name == "".
Assert.That(destinationInfo.Info1.Name, Is.EqualTo("field name 1"));
}
}
这是预期的行为吗?我怎样才能达到我想要的?实体类中有大量字段,因此此解决方法对我不起作用。