我正在做一个非常简单的测试,我想将属性的值保留在目标实体中。
我有2节课:
public class Model_Source
{
public int Prop_A { get; set; }
public string Prop_B { get; set; }
public string Prop_C { get; set; }
}
public class Model_Destination
{
public int Prop_A { get; set; }
public string Prop_B { get; set; }
public string Prop_C { get; set; }
}
我已经配置了自动映射器,以将 Model_Destination 类别的 Prop_C 的目标值保持不变:
public class AutomapperProfileSetting : Profile
{
public AutomapperProfileSetting()
{
//<TSource, TDestination>
this.CreateMap<Model_Source, Model_Destination>()
.ForMember(source => source.Prop_C, opt => opt.UseDestinationValue());
}
}
这是我使用xunit的测试方法:
[Fact]
public async Task MapTest_UseDestinationValue()
{
//ARRANGE
//----------------------
//auto mapper configuration
var mockMapper = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutomapperProfileSetting());
});
IMapper mapper = mockMapper.CreateMapper();
Model_Source model_Source = new Model_Source();
model_Source.Prop_A = 111;
model_Source.Prop_B = "Source VALUE B";
model_Source.Prop_C = "Source VALUE C";
Model_Destination model_Destination = new Model_Destination();
model_Destination.Prop_A = 222;
model_Destination.Prop_B = "Destination VALUE B";
model_Destination.Prop_C = "Destination VALUE C - UNCHANGED";
//ACT
//----------------------
model_Destination = mapper.Map<Model_Source, Model_Destination>(model_Source);
}
测试运行后,model_Destination属性值为:
model_Destination.Prop_A == 222 //<--NOT EXPECTED
model_Destination.Prop_B == "Destination VALUE B" //<--NOT EXPECTED
model_Destination.Prop_C == "Source VALUE C" //<--NOT EXPECTED, was expecting "Destination VALUE C - UNCHANGED"???
我期望的model_Destination属性值的值为:
model_Destination.Prop_A == 111
model_Destination.Prop_B == "Source VALUE B"
model_Destination.Prop_C == "Destination VALUE C - UNCHANGED"
最后,Prop_C应该没有被更改,值应该是“ Destination VALUE C-UNCHANGED”,为什么?
p.s。 我使用的是AutoMapper.Extensions.Microsoft.DependencyInjection v6.0.0,具有对automapper 8.0.0和.net core 2.2.0的依赖关系