Sandeep Reddy Pinniti
Sandeep Reddy Pinniti

Reputation: 431

Unmapped field on destination is set to null

I am using Automapper for mapping two objects.

I have field VehicleModel in the destination which has some default value. I don't have a mapping for this destination field in the source. So I didn't map it. After mapping is done, my default value is set to null value on the destination. The data objects looks like below.

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

Mapping between Source and OutputData.

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

How to avoid this behavior.

Thanks in advance. Sandeep

Upvotes: 0

Views: 453

Answers (1)

k0stya
k0stya

Reputation: 4315

I have modified the code to make it compilable. Correct if something is wrong.

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

Note: I added default model.

With you configuration and above code the following mapping works as you expected:

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

So looks like you some important piece of code is not provided.

Upvotes: 1

Related Questions