I have the following classes. Domain models are created by entity framework and I use POCO.
public class Customer { public int Id { get; set; } public string Name { get; set; } public DateTime CreatedDate{ get; set; } public DateTime ModifiedDate{ get; set; } public virtual ICollection<Order> Orders{ get; set; } } public class CustomerDTO { public int Id { get; set; } public string Name{ get; set; } public List<OrderDTO> Orders{ get; set; } } public class Order { public int Id { get; set; } public string Name { get; set; } public int ProductId { get; set; } public DateTime CreatedDate{ get; set; } public DateTime ModifiedDate{ get; set; } } public class OrderDTO { public int Id { get; set; } public string Name{ get; set; } }
I tried the following comparisons.
Mapper.CreateMap<Customer, CustomerDTO>(); Mapper.CreateMap<CustomerDTO, Customer>(); Mapper.CreateMap<Order, OrderDTO>(); Mapper.CreateMap<OrderDTO, Order>();
I also tried
Mapper.CreateMap<CustomerDTO, Customer>().ForMember(c => c.Orders, m => m.MapFrom ( q => Mapper.Map<List<OrderDTO>, ICollection<Order>>(q.Orders) ) );
To update the client, I retrieve it from the database and update it using customerDTO
Customer customer = _customerRepository.GetById(customerDTO.Id); Mapper.Map<CustomerDTO, Customer>(customerDTO, customer);
The client object is updated correctly, and the created and changed date are not changed. But each order in the list of orders is not updated correctly. Its productId, created and modified dates are set to the default value, not the values that are retrieved from the database.
Do I need to do something because Orders is a virtual collection?
I am new to auto mapper with any appreciation.
EDIT
I added
Mapper.AssertConfigurationIsValid();
When starting the application, the following error appeared: Unconnected members were found. Browse the types and elements below. Add a custom display expression, ignore, add a custom converter, or change the source / destination type
I updated my mapping to:
Mapper.CreateMap<OrderDTO, Order>() .ForMember(x => x.CreatedDate, y => y.Ignore()) .ForMember(x => x.ModifiedDate, y => y.Ignore()) .ForMember(x => x.ProductId, y => y.Ignore())
But the order still has the properties listed above, overwritten by default vale