0

I have an Employee class with Addresses as a property in it as shown below and respective DTO's EmployeeDTO and AddressDTO

public class EmployeeDTO {
    public string Name { get; set; }
    public IList<AddressDTO> Addresses { get; set; }
}

public class Employee {
    public virtual string Name { get; set; }
    public virtual IList<Address> Addresses { get; set; }
}

My AutoMapper Mappings are little more than this, but for sake of easiness I'm just showing direct mapping.

Mapper.CreateMap<EmployeeDTO, Employee>();
Mapper.CreateMap<Employee, EmployeeDTO>();

Mapper.CreateMap<AddressDTO, Address>();
Mapper.CreateMap<Address, AddressDTO>();

In my datalayer I get a Employee by its Name and then convert it to EmployeeDTO and transfer it to UI. In the UI I change an Address or add a new address to the Addresses of EmployeeDTO and transfer it back to the server to persist. In the Repository I get the existing Employee from the db and then use AutoMapper to update the object. I use AutoMapper's Map overload to give the the same entity back

TDestination Map<TSource, TDestination>(TSource source, TDestination destination);
var empObj = Mapper.Map<EmployeeDTO, Employee>(updatedDTO, empInDb);

I use session's SaveOrUpdate to persist

_session.SaveOrUpdate(empObj);

On committing this throws exception saying

"a different object with the same identifier value was already associated with the session: 4, of entity: Address"

If I use _session.Merge it work fine, but previously when I use manual mapping instead of AutoMapper it worked fine with 'session.SaveOrUpdate.'

  1. So what's going wrong when I map using AutoMapper. I guess inside automapper when it see a mapping between List and List it just uses the normal map. can we specify somewhere so that AutoMapper uses the overload of Map so that it returns the same entity.
  2. I saw a small speed difference between SaveOrUpdate and Merge. Anyway to speed it up.
  • possible unanswered duplicate [Mapping Child Collections using AutoMapper](http://stackoverflow.com/questions/20253074/mapping-child-collections-using-automapper) – Rino Reji Cheriyan Dec 19 '14 at 08:14

1 Answers1

0

Complex reverse mapping with AutoMapper isn't supported. Mapping collections is hard. You'd have to merge two collections, deleting what doesn't exist, adding new things etc. You'd also have to define some mechanism on how to match an existing source DTO to a destination model.

If you wrote the reverse code manually, you'd see what you're up against. Don't reverse map complex objects, it's not supported and likely never will.

Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69
  • For the sake of understandability I have simplified the code above. In my actual code I have specified how to map each property from DTO to BO and also from BO to DTO (separately). AutoMapper is mapping the objects perfectly. I'm getting error from the NHibernate part only. – Rino Reji Cheriyan Dec 19 '14 at 14:12