AutoMapper 3.1.1을 사용하는 프로젝트가 있는데, 내가 겪고있는 문제를 격리 할 수있었습니다. 여기AutoMapper에서 예기치 않은 매핑이 발생하는 이유는 무엇입니까?
내 테스트 클래스입니다 :
다음class BaseClass
{
public string PropertyA { get; set; }
}
class DerivedClass: BaseClass
{
public string PropertyB { get; set; }
}
class ContainerClass
{
public DerivedClass ComplexProperty { get; set; }
public string PropertyC { get; set; }
}
class SourceClass
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
내 매핑 규칙은 다음과 같습니다
가var source = new SourceClass {
PropertyA = "ValueA",
PropertyB = "ValueB",
PropertyC = "ValueC",
};
var destination = Mapper.Map<ContainerClass>(source);
Console.WriteLine("PropertyA: " + destination?.ComplexProperty?.PropertyA);
Console.WriteLine("PropertyB: " + destination?.ComplexProperty?.PropertyB);
Console.WriteLine("PropertyC: " + destination?.PropertyC);
출력은 다음과 같습니다 :
PropertyA: ValueA
PropertyB:
PropertyC: ValueC
다음
Mapper.CreateMap<SourceClass, ContainerClass>()
.ForMember(d => d.ComplexProperty, o => o.MapFrom(s => Mapper.Map<DerivedClass>(s)))
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("SourceClass-> ContainerClass mapped"));
Mapper.CreateMap<SourceClass, DerivedClass>()
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("SourceClass -> DerivedClass mapped"));
Mapper.CreateMap<BaseClass, DerivedClass>()
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("BaseClass -> DerivedClass mapped"));
내 코드입니다
PropertyB의 값이 "ValueB"가 될 것으로 예상했지만 값은 null입니다. 그것은 BaseClass에서 DerivedClass 로의 매퍼가 어떤 이유로 실행되기 때문에 발생합니다. 내 디버그 출력은 다음과 같습니다 :
SourceClass -> DerivedClass mapped
BaseClass -> DerivedClass mapped
SourceClass -> ContainerClass mapped
왜 AutoMapper는 BaseClass -> DerivedClass 매핑을 실행합니까?
UPDATE : 마리우스에 감사 내가 지금 DerivedClass에 BaseClass로에서 해당 매핑이 잘못 알고있다. 그가 제안한대로이 매핑 규칙을 제거 할 수 없습니다. 왜냐하면 내 응용 프로그램에 필요하기 때문입니다.
Mapper.CreateMap<BaseClass, DerivedClass>()
.ForMember(d => d.PropertyB, o => o.Ignore())
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("BaseClass -> DerivedClass mapped"));
을 지금 Mapper.AssertConfigurationIsValid();
더 이상 예외를 발생하지 않습니다 예외가 있듯이 나는 PropertyB에 대한 무시했다. 그러나 원래의 문제는 여전히 남아 있습니다. AutoMapper가 BaseClass -> DerivedClass 매핑을 실행하는 이유는 무엇입니까? AutoMapper 문제를 디버깅 할 때
질문이 업데이트되었습니다. BaseClass -> DerivedClass 만 제거 할 수는 없지만 응용 프로그램에 필요합니다. –