繁体   English   中英

将多个参数传递给自动映射器

[英]Pass multiple parameters to 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。 以下是我到目前为止所做的事情。 但是,我无法映射名称和型号。 如何将这些参数传递给自动映射器? 我对身份所做的一切还可以吗?

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. 如果在CarContract类中默认未初始化Properties对象。
  2. 要映射回状态和模型,您应该使用Enum.Parse方法。
  3. status始终设置为“就绪”状态,而不是映射的对象值。

使用以下代码:

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

确保将<>替换为适当的枚举。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM