将多个参数传递给automapper

时间:2018-05-07 05:08:42

标签: c# parameters automapper

我的域对象和合同之间有一个映射,如下所示: -

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

    string model{ get; set; }

    CarProperties properties { get; set; }
}

public class CarProperties 
{
    string color { get; set; }

    string type { get; set; }
}

public class CarContract
{
    string name { get; set; }

    string model{ get; set; }

    string color { get; set; }

    string type { get; set; }

    string status { get; set; }
}

public static Car GetCreateCarPayloadFromCarContract(CarContract carContract, string name, ModelType modelType)
{
    var car= new Car
    {
        name = name,
        model= modelType.ToString(),
        properties = new CarProperties
        {
            color = carContract.color,
            type = carContract.type
        },
        status = Status.READY.ToString()
    };

    return car;
}

此处ModelType和Status是枚举。我试图将GetCreateCarPayloadFromCarContract方法转换为使用automapper。以下是我到目前为止所做的事情。但是我无法映射名称和型号。如何将这些参数传递给automapper?我所做的地位也很好吗?

CreateMap<Car,CarContract>()
    .ForMember(dest => dest.color, opt => opt.MapFrom(src => src.properties.color))
    .ForMember(dest => dest.type, opt => opt.MapFrom(src => src.properties.type))
    .ReverseMap()
    .ForMember(dest => dest.properties.color, opt => opt.MapFrom(src => src.color))
    .ForMember(dest => dest.properties.type, opt => opt.MapFrom(src => src.type))
    .ForMember(dest => dest.status, opt => opt.MapFrom(src => Status.READY.ToString()))

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我相信您的代码有以下观察

  1. 如果Properties对象在默认情况下未初始化,则为 CarContract课程。
  2. 要映射状态和模型,您应该Enum.Parse方法。
  3. status始终设置为Ready状态而不是映射对象值。
  4. 使用以下代码:

          CreateMap<Car,CarContract>()
         .ForMember(dest => dest.color, opt => opt.MapFrom(src => 
          src.properties.color))
          .ForMember(dest => dest.type, opt => opt.MapFrom(src => 
          src.properties.type))
         .ForMember(dest => dest.model, opt => opt.MapFrom(src => (<<Your Model 
          Enum Type>>)Enum.Parse(typeof(<<Your Model Enum Type>>), src.model)))
         .ForMember(dest => dest.status, opt => opt.MapFrom(src => (<<Your Status 
          Enum Type>>)Enum.Parse(typeof(<<Your Status Enum Type>>), src.status)))
         .ReverseMap()
         .ForMember(dest => dest.properties, opt => opt.MapFrom(src => new 
         CarProperties() { color = src.color, type = src.type }))
         .ForMember(dest => dest.status, opt => opt.MapFrom(src => src.status.ToString()))
         .ForMember(dest => dest.model, opt => opt.MapFrom(src => src.model.ToString()))
    
      

    确保替换&lt;&gt;适当的枚举。