使用自动映射器配置文件将2种不同类型映射为一种

时间:2018-12-07 09:16:11

标签: c# automapper

是否可以将两个不同的对象映射(使用AutoMapper)到同一对象中?如何实现?

下面是一个描述案例的示例(请记住,这是一个概念上的示例):

namespace AutomapperTest.Profiles
{
    public class CarWrapper
    {
        public CarWrapper(Car car, string customerName)
        {
            CustomerName = customerName;
            Car = car;
        }

        public string CustomerName { get; set; }
        public Car Car { get; set; }
    }

    public class Car
    {
        public string ModelName { get; set; }
        public int SerialNumber { get; set; }
    }

    public class CarView
    {
        public string Customer { get; set; }
        public string Model { get; set; }
        public int Serial { get; set; }
    }

    public class CarProfile : Profiles
    {
        public CarProfile()
        {
            // Map profile of Car with specific add-ons from CarWrapper
            CreateMap<CarWrapper, CarView>()
                .ForMember(dst => dst.Customer, opt => opt.MapFrom(src => src.CustomerName))
                .ForMember(dst => dst, opt => opt.MapFrom(src => src.Car)); // <-- This will throw an exception.

            // Map profile of Car
            CreateMap<Car, CarView>()
                .ForMember(dst => dst.Model, opt => opt.MapFrom(src => src.ModelName))
                .ForMember(dst => dst.Serial, opt => opt.MapFrom(src => src.SerialNumber));
        }
    }
}

我想做的是告诉第一个CreateMap对父级的嵌套类型使用另一个CreateMap:

.ForMember(dst => dst, opt => opt.MapFrom(src => src.Car));

0 个答案:

没有答案