2012-07-26 5 views
0

두 개체를 매핑하는 데 Automapper를 사용하고 있습니다.대상의 매핑되지 않은 필드가 null로 설정되었습니다.

대상에 일부 기본값이있는 VehicleModel 필드가 있습니다. 원본에있는이 대상 필드에 대한 매핑이 없습니다. 그래서 나는 그것을지도 화하지 않았다. 매핑이 완료되면 내 기본값이 대상에서 null 값으로 설정됩니다. 데이터 객체는 아래와 같습니다.

public partial class Source 
{ 

private Car[] cars; 

public Car[] Cars 
{ 
    get { return this.cars; } 
    set { this.cars = value; } 
} 
} 

public partial class Destination 
{ 
private OutputData output; 

public OutputData Output 
{    
    get { return this.output; } 
    set { this.output= value; } 
} 
} 

public class OutputData 
{ 
private List<Cars> cars; 
private string vehicleModel; 

public Car[] Cars 
{ 
    get { return this.cars; } 
    set { this.cars = value; } 
} 
public string VehicleModel 
{    
    get { return this.vehicleModel; } 
    set { this.vehicleModel= value; } 
} 
}  

소스와 OutputData 간의 매핑.

Mapper.CreateMap<Source, OutputData>(); 
Mapper.CreateMap<Source, Destination>().ForMember(dest => dest.Output, input => 
    input.MapFrom(s=>Mapper.Map<Source, OutputData>(s))); 

이 동작을 방지하려면 어떻게해야합니까?

미리 감사드립니다. Sandeep

+1

CreateMap과 클래스 정의가 도움이 될 것입니다. 그러나 Mapper.Map을 호출 할 때 대상 객체를 제공합니까? – PatrickSteele

+0

데이터 모델에 대한 내 이전 게시물을 참조하시기 바랍니다 http://stackoverflow.com/questions/11633021/automapper-expression-must-resolve-to-top-level-member 공용 클래스 OutputData { 개인 목록 자동차; 전용 문자열 vehicleModel; 공용 자동차 [] 자동차 { get {return this.cars; } set {this.cars = value; } } public String VehicleModel { get {return this.vehicleModel; } set {this.vehicleModel = value; } } } VehicleModel 필드에 매핑하기 전에 일부 값이 있습니다. 소스에 매핑 필드가 없습니다. 매핑 한 후 VehicleModel이 Null로 설정됩니다. –

+1

질문에 코드를 추가하여 해당 코드를 읽을 수있게하고 다른 사람들이 도움을 받아 의견을 검토 할 필요가 없도록하십시오. – PatrickSteele

답변

1

나는 코드를 수정하여 컴파일 가능하게 만들었습니다. 잘못된 것이 있으면 수정하십시오.

public class Car 
{ 
    public string Brand {get;set;} 
} 

public partial class Source 
{ 
    private Car[] cars; 

    public Car[] Cars 
    { 
     get { return this.cars; } 
     set { this.cars = value; } 
    } 
} 

public partial class Destination 
{ 
    private OutputData output; 

    public OutputData Output 
    {    
     get { return this.output; } 
     set { this.output= value; } 
    } 
} 

public class OutputData 
{ 
    private List<Car> cars; 
    private string vehicleModel = "DEFAULTMODEL"; 

    public Car[] Cars 
    { 
     get { return cars.ToArray(); } 
     set { this.cars = value.ToList(); } 
    } 
    public string VehicleModel 
    {    
     get { return this.vehicleModel; } 
     set { this.vehicleModel= value; } 
    } 
}  

참고 : 기본 모델을 추가했습니다. 예상대로 다음 매핑하면 구성으로 코드 위

작동 :

var res = Mapper.Map<Source, Destination>(new Source { Cars = new Car[]{ new Car{ Brand = "BMW" }}}); 

그래서 코드의 몇 가지 중요한 부분이 제공되지 않습니다 당신처럼 보인다.