0
votes

I'm new to automapper and I'm trying very simple map. I have the following class and I', trying to map personmodel to person. It keeps failing at orders. Sorry if this silly but I could not figure out. I removed all properties on orders to see what is wrong

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
You need to create map for Orders as well. You must be having Orders entity in both Person and PersonModel. So you need to create a Map for Orders entity in both Person and PersonModel. AutoMapper looks for maps recursively inside an object. It couldn't find map for Orders. Hence it is failing. - Venky

2 Answers

1
votes

Create Map between Orders and OrderModel.

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

I use this code for map a list<>

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

and:

 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);
            }
    }