带父/子的自动映射和自定义类型转换器

时间:2011-12-24 06:15:16

标签: automapper

如何根据使用automapper保存当前对象的父对象的属性,将对象转换为某种类型?

下面我有一个包含枚举类型Type的{​​{1}}属性的类。我想将属性EventAssetType转换为名为AssetDocumentModel的类型,它们都使用ImageModel属性从AssetModel继承。现在它只是从Type映射到Asset

AssetModel

1 个答案:

答案 0 :(得分:1)

实现此目的的一种方法是在创建地图时使用ConvertUsing扩展方法。我在下面为你提供了一个例子:

namespace Some.Namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.CreateMap<Source, Animal>().ConvertUsing(MappingFunction);

            Source animal = new Source() {Type = Source.SourceType.Animal, Name = "Some Animal"};
            Source dog = new Source() {Type = Source.SourceType.Dog, Name = "Fido"};

            Animal convertedAnimal = Mapper.Map<Source, Animal>(animal);
            Console.WriteLine(convertedAnimal.GetType().Name + " - " + convertedAnimal.Name);
            // Prints 'Animal - Some Animal'

            Animal convertedDog = Mapper.Map<Source, Animal>(dog);
            Console.WriteLine(convertedDog.GetType().Name + " - " + convertedDog.Name);
            // Prints 'Dog - Fido'
        }

        private static Animal MappingFunction(Source source)
        {
            switch (source.Type)
            {
                    case Source.SourceType.Animal:
                    return new Animal() {Name = source.Name};
                    case Source.SourceType.Dog:
                    return new Dog() {Name = source.Name};
            }
            throw new NotImplementedException();
        }
    }

    public class Source
    {
        public enum SourceType
        {
            Animal,
            Dog
        }

        public string Name { get; set; }

        public SourceType Type { get; set; }
    }

    public class Animal
    {
        public string Name { get; set; }
    }

    public class Dog : Animal
    {
        // Specific Implementation goes here
    }
}