2011-12-24 10 views
1

オートマトンで現在のオブジェクトを保持している親オブジェクトのプロパティに基づいてオブジェクトを特定のタイプに変換するにはどうすればよいですか?オートマトンと親子のカスタムタイプコンバータ

以下、という列挙型のプロパティEventAssetTypeを含むクラスがあります。 AssetのプロパティをDocumentModelまたはImageModelというタイプに変換し、両方ともから継承し、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つの方法は、マップを作成するときに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 
    } 
}