目标上的未映射字段设置为null

时间:2012-07-26 10:29:22

标签: .net automapper automapper-2

我使用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 个答案:

答案 0 :(得分: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" }}});

所以看起来你没有提供一些重要的代码。