Receiving this error:
a different object with the same identifier value was already associated with the session: 27, of entity: xxx.Core.Event
Basically, I have view models that are being mapped from my poco’s and vice versa. The offending code is here:
Mapper.CreateMap<EventsAddEditViewModel, Event>();
Event thisEvent = _eventRepository.GetById(viewModel.Id);
thisEvent = Mapper.Map<EventsAddEditViewModel, Event>(viewModel);
thisEvent.EventType = new EventType { Id = viewModel.EventTypeId };
ValidationResult result = _eventService.Save(thisEvent);
Basically I’m loading the event from the database, and then mapping the view model to this event and saving. Otherwise there are fields that aren’t shown on the view (dateCreated for example) which won’t be saved properly.
Is there any way that NHibernate and AutoMapper can play nicely in this regard?
I’m using OnePerRequestBehavior for my session provider.
Give NHibernate same object back when you save.
To do this we we use a different overload of
Mapper.Map(). Also, when the compiler can figure out the types there is no need to specify them.Also
GetById()might return a null.