Automapper и Custom Type Converter с родителем / потомком - PullRequest
1 голос
/ 24 декабря 2011

Как я могу скрыть объект определенного типа, основанный на свойстве родительского объекта, содержащего текущий объект с помощью автоматического средства?

Ниже у меня есть класс, который содержит свойство с именем Type типа enumEventAssetType.Я хочу преобразовать свойство Asset в тип с именем DocumentModel или ImageModel, которые оба наследуются от AssetModel, используя свойство Type.Прямо сейчас это просто отображение от Asset до AssetModel.

public class EventAssetModel
{
    public EventAssetModel()
    {
        Event = new EventModel();
        Asset = new DocumentModel();
        Type = Enums.EventAssetType.Other;
    }

    public int Id { get; set; }
    public bool Active { get; set; }
    public Enums.EventAssetType Type { get; set; }

    public EventModel Event { get; set; }
    public AssetModel Asset { get; set; }
}

1 Ответ

1 голос
/ 28 декабря 2011

Один из способов сделать это - метод расширения 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
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...