문제

소스 속성의 값에 따라 멤버 매핑을 무시할 수 있습니까?

예를 들어 우리가 가지고있는 경우 :

public class Car
{
    public int Id { get; set; }
    public string Code { get; set; }
}

public class CarViewModel
{
    public int Id { get; set; }
    public string Code { get; set; }
}

나는 같은 것을 찾고 있습니다

Mapper.CreateMap<CarViewModel, Car>()
      .ForMember(dest => dest.Code, 
      opt => opt.Ignore().If(source => source.Id == 0))

지금까지 내가 가진 유일한 솔루션은 두 가지 다른 뷰 모델을 사용하고 각 모델마다 다른 매핑을 만드는 것입니다.

도움이 되었습니까?

해결책

이 멤버는 구성 유효성 검사에서 건너 뜁니다. 몇 가지 옵션을 확인했지만 사용자 정의 값 리졸버가 트릭을 수행하는 것처럼 보이지 않습니다.

사용 상태() 조건이 참을 때 멤버를 매핑하는 기능 :

Mapper.CreateMap<CarViewModel, Car>()
 .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id != 0))

다른 팁

나는 비슷한 문제에 부딪쳤다. 그리고 이것은 기존 값을 덮어 쓸 것이다. dest.Code NULL을 사용하면 출발점으로 도움이 될 수 있습니다.

AutoMapper.Mapper.CreateMap().ForMember(dest => dest.Code,config => config.MapFrom(source => source.Id != 0 ? null : source.Code));

조건부 매핑의 문서는 다음과 같습니다.http://docs.automapper.org/en/latest/conditional-mapping.html

매핑 프로세스에서 소스 값이 해결되기 전에 실행되기 때문에 특정 시나리오에서 Precondition이라는 또 다른 방법이 있습니다.

Mapper.PreCondition<CarViewModel, Car>()
 .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id == 0))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top