automapper - ignore mapping if property type is different with same property name - C#

后端 未结 3 1290
抹茶落季
抹茶落季 2021-01-12 03:24

How can I ignore mapping if property type is different with same property name? By default it\'s throwing error.

Mapper.CreateMap

        
3条回答
  •  孤城傲影
    2021-01-12 04:16

    One way to process all properties for type is to use .ForAllMembers(opt => opt.Condition(IsValidType))). I have used new syntax for AutoMapper usage, but it should work even with old syntax.

    using System;
    using AutoMapper;
    
    namespace TestAutoMapper
    {
        class Program
        {
            static void Main(string[] args)
            {
                var mapperConfiguration = new MapperConfiguration(cfg => cfg.CreateMap()
                    .ForAllMembers(opt => opt.Condition(IsValidType))); //and how to conditionally ignore properties
                var car = new Car
                {
                    VehicleType = new AutoType
                    {
                        Code = "001DXT",
                        Name = "001 DTX"
                    },
                    EngineName = "RoadWarrior"
                };
    
                IMapper mapper = mapperConfiguration.CreateMapper();
                var carDto = mapper.Map(car);
                Console.WriteLine(carDto.EngineName);
    
                Console.ReadKey();
            }
    
            private static bool IsValidType(ResolutionContext arg)
            {
                var isSameType = arg.SourceType== arg.DestinationType; //is source and destination type is same?
                return isSameType;
            }
        }
    
        public class Car
        {
            public AutoType VehicleType { get; set; } //same property name with different type
            public string EngineName { get; set; }
        }
    
        public class CarDto
        {
            public string VehicleType { get; set; } //same property name with different type
            public string EngineName { get; set; }
        }
    
        public class AutoType
        {
            public string Name { get; set; }
            public string Code { get; set; }
        }
    }
    

提交回复
热议问题