如何根据使用automapper保存当前对象的父对象的属性,将对象转换为某种类型?
下面我有一个包含枚举类型Type
的{{1}}属性的类。我想将属性EventAssetType
转换为名为Asset
或DocumentModel
的类型,它们都使用ImageModel
属性从AssetModel
继承。现在它只是从Type
映射到Asset
。
AssetModel
答案 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
}
}