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.'
- 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.
- I saw a small speed difference between SaveOrUpdate and Merge. Anyway to speed it up.