C#Automapper->条件映射

时间:2018-07-31 14:54:54

标签: c# conditional automapper

我正在尝试进行条件映射,而我已阅读的所有文档和问题似乎都没有涵盖此特定条件。我希望这里的人能有经验或知道如何以最佳方式解决此问题。

我正在映射具有两个属性的对象。但是,如果特定属性具有值,则我不想映射EITHER属性。要可视化此内容:

head

但是,我想要与上述声明等效的else { ... }。所以更像是:

foreach(var object in objectB) {
    If (object.propertyA == "SomeValue")
        continue;
    else
        Mapper.Map<ObjectA>(object);
}

但是上述版本显然不起作用。 预先感谢您的协助。

1 个答案:

答案 0 :(得分:3)

可以使用条件映射来实现,有关详细信息,请参见文档(http://docs.automapper.org/en/latest/Conditional-mapping.html)。为了介绍数组过滤的情况,我创建了一个自定义类型转换器,这有点棘手(请参阅http://docs.automapper.org/en/stable/Custom-type-converters.html)。更新后的示例如下

using AutoMapper;
using System;
using System.Collections.Generic;

namespace ConsoleAppTest2
{
    class Program
    {
        static void Main(string[] args)
        {

            Mapper.Initialize(cfg => {
                //Using specific type converter for specific arrays
                cfg.CreateMap<Foo[], FooDto[]>().ConvertUsing(new ArrayFilterTypeConverter<Foo[], FooDto[], Foo, FooDto>(
                                                                                                               (src, dest) => (src.Age > 0)
                                                                                                            ));

                cfg.CreateMap<Foo, FooDto>()
                    .ForMember(dest => dest.Age, opt => opt.Condition(src => (src.Age >= 0)))
                    .ForMember(dest => dest.CurrentAddress, opt =>
                                                                {
                                                                    opt.Condition(src => (src.Age >= 0));
                                                                    opt.MapFrom(src => src.Address);
                                                                });

            });

            var foo = new Foo() { Name = "Name", Address = "Address", Age = -1 };
            var fooDTO = new FooDto();


            var fooArray = new Foo[] {
                    new Foo() { Name = "Name1", Address = "Address1", Age = -1 },
                    new Foo() { Name = "Name2", Address = "Address2", Age = 1 },
                    new Foo() { Name = "Name3", Address = "Address3", Age = 1 }
            };

            var fooDTOArray =  Mapper.Map<Foo[], FooDto[]>(fooArray); //get 2 elements instead of 3

            Mapper.Map(foo, fooDTO);
            //The result is we skipped Address and Age properties becase Age is negative

            Console.ReadLine();
        }
    }

    public class ArrayFilterTypeConverter<TSourceArray, TDestArray, TSource, TDest> : ITypeConverter<TSourceArray, TDestArray>
    {
        private Func<TSource, TDest, bool> filter;

        public ArrayFilterTypeConverter(Func<TSource, TDest, bool> filter)
        {
            this.filter = filter;
        }

        public TDestArray Convert(TSourceArray source, TDestArray destination, ResolutionContext context)
        {
            var sourceArray = source as TSource[];
            List<TDest> destList = new List<TDest>();

            var typeMap = context.ConfigurationProvider.ResolveTypeMap(typeof(TSource), typeof(TDest));

            foreach (var src in sourceArray)
            {
                var dest = context.Mapper.Map<TSource, TDest>(src);

                if (filter(src, dest))
                    destList.Add(dest);
            }

            // Little hack to cast array to TDestArray
            var result = (TDestArray)(object)destList.ToArray();
            return result;
        }
    }

    internal class FooDto
    {
        public string Name { get; set; }
        public string CurrentAddress { get; set; }
        public int Age { get; set; }

    }

    internal class Foo
    {
        public string Name { get; set; }
        public string Address { get; set; }

        public int Age { get; set; }
    }
}