使用automapper错误映射类型

时间:2017-05-21 18:29:59

标签: c# automapper

我是自动播放器的新手,我正在尝试非常简单的地图。我有以下课程和我',试图将人物模型映射到人。 它一直在订单失败。对不起,如果这个愚蠢,但我无法弄清楚。我删除了订单上的所有属性以查看错误

public class Person
{
    public Person()
    {
        Orders = new List<Orders>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Id { get; set; }


    public List<Orders> Orders { get; set; }
}

public class Orders
{
    public string OrderName { get; set; }

}

public class PersonModel
{
    public PersonModel()
    {
        Orders = new List<OrderModel>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Id { get; set; }
    public List<OrderModel> Orders { get; set; }
}

public class OrderModel
{
      public string OrderName { get; set; }

}

I have the mapper defined as Mapper.Initialize(x => x.CreateMap<PersonModel, Person>());
The error that I get is:
Error mapping types.

Mapping types:
PersonModel -> Person
PersonModel -> Person

Type Map configuration:
PersonModel -> Person
PersonModel -> Person

Property:
Orders

2 个答案:

答案 0 :(得分:1)

在订单和OrderModel之间创建地图。

Mapper.CreateMap<Orders, OrderModel>().ReverseMap();

答案 1 :(得分:-1)

我使用此代码映射列表<>

var result = NewMapperHelper.MapList<OrderModel, Orders>(YourSource);

和:

 public static class NewMapperHelper
  {
        public static List<TDestination> MapList<TDestination, TSource> 
             (List<TSource> entity)
            {            
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<TSource, TDestination>().ReverseMap();
                });
    
                var _mapper = config.CreateMapper();
                return _mapper.Map<List<TDestination>>(entity);
            }
    }