2012-07-26 47 views
0

我正在使用Automapper來映射兩個對象。目標上未映射的字段設置爲空

我在有目的地有一些默認值的現場VehicleModel。源中沒有此目標字段的映射。所以我沒有繪製它。映射完成後,我的默認值在目標上設置爲空值。數據對象如下所示。

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; } 
} 
}  

Source和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 2012-07-26 12:33:21

+0

請參考我先前的職位數據模型 http://stackoverflow.com/questions/11633021/automapper-expression-must-resolve-to-top-level-member 公共類OutputData { 私有列表車;私家車車模 ; public car []汽車 { get {return this.cars; } set {this.cars = value; } } public String VehicleModel {{{return this.vehicleModel; } set {this.vehicleModel = value; } } } VehicleModel字段在映射之前有一些值。它在源代碼中沒有映射字段。將VehicleModel設置爲Null後映射後 – 2012-07-26 14:03:17

+1

請將代碼添加到問題中以使其可讀,其他人可能無需通過評論進行篩選。 – PatrickSteele 2012-07-26 14:30:18

回答

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" }}}); 

所以看起來你沒有提供的代碼的一些重要部分。