Automapper instantiates destination object instead of mapping recursively
I am trying to map my DTO object to entity object in my factory class. DTO has all field values straight, whereas entity has fields which consist of Name and Value.
After some debugging, I found Automapper instantiates each entity fields instead of using existing one. As a result, the last test fails.
[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"));
}
}
Is this expected behavior? How can I achieve what I want? There are tons of fields in the entity classes so this workaround will not work for me.
Try changing your second map to:
Mapper.CreateMap<SourceInfo, DestinationInfo>()
.ForAllMembers(x => x.UseDestinationValue());
This should use destination values for all un-mapped attributes.
链接地址: http://www.djcxy.com/p/37424.html