我正在尝试将多种类型,大约50种映射到其他类型(其中50种),它们是1对1,但我想从接口映射到具体类型。
相关代码示例:
using AutoMapper;
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
public interface IAnimalBO { }
public interface IBearBO : IAnimalBO { }
public interface ITigerBO : IAnimalBO { }
public static void Main()
{
var config = new MapperConfiguration(cfg =>
{
// Base class mapping..
cfg.CreateMap<IAnimalBO, AnimalVM>();
cfg.CreateMap<ITigerBO, TigerVM>();
cfg.CreateMap<IBearBO, BearVM>();
});
var mapper = config.CreateMapper();
// Configure AutoMapper
var businessObjects = new List<IAnimalBO>
{
new TigerBO(),
new BearBO()
};
var results = mapper.Map<IEnumerable<AnimalVM>>(businessObjects);
foreach (var result in results)
{
Console.WriteLine(result.GetType().Name);
}
Console.ReadKey();
}
public class AnimalVM { }
public class BearBO : IBearBO { }
public class BearVM : AnimalVM { }
public class TigerBO : ITigerBO { }
public class TigerVM : AnimalVM { }
}
}
预期输出应为:
TigerVM
BearVM
但实际输出是:
AnimalVM
AnimalVM
我不确定如何设置automapper来映射这些类型。
如果我推荐基线映射:
// Base class mapping..
// cfg.CreateMap<IAnimalBO, AnimalVM>();
然后我得到以下异常:
映射类型时出错。
映射类型:
List'1 - &gt; IEnumerable'1 System.Collections.Generic.List'1 [[ConsoleApplication1.Program + IAnimalBO,ConsoleApplication1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]] - &gt; System.Collections.Generic.IEnumerable'1 [[ConsoleApplication1.Program + AnimalVM,ConsoleApplication1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]
答案 0 :(得分:2)
您想要使用 include&lt;&gt; ,它会从类中选择派生最多的映射。
Mapping Inheritance的更多信息。
var config = new MapperConfiguration(cfg =>
{
// Base class mapping..
cfg.CreateMap<IAnimalBO, AnimalVM>()
.Include<ITigerBO, TigerVM>()
.Include<IBearBO, BearVM>();
cfg.CreateMap<ITigerBO, TigerVM>();
cfg.CreateMap<IBearBO, BearVM>();
});