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

如何避免这种行为。

提前致谢。桑迪普

4

1 回答 1

1

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.

于 2012-07-27T23:55:28.813 回答