我正在尝试将我的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"));
}
}
这是预期的行为吗?我怎样才能实现我的目标?实体类中有大量字段this workaround will not work for me。
答案 0 :(得分:1)
尝试将第二张地图更改为:
Mapper.CreateMap<SourceInfo, DestinationInfo>()
.ForAllMembers(x => x.UseDestinationValue());
这应该使用所有未映射属性的目标值。