NHibernate and AutoMapper do not play well: "another object with the same identifier value already existed"

Getting this error: another object with the same identifier value was already associated with the session: 27, object: xxx.Core.Event

Basically, I have view models that display from my poco and vice versa. Violation code 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); 

I basically load the event from the database, and then map the view model to this event and save. Otherwise, there are fields that are not displayed in the view (for example, dateCreated) that will not be saved properly.

Is there a way that NHibernate and AutoMapper can play well in this regard?

I am using OnePerRequestBehavior for my session provider.

+4
source share
2 answers

Give NHibernate the same object back when saving.

To do this, we use another overload of Mapper.Map() . In addition, when the compiler can determine the types, there is no need to specify them.

Also GetById() can return zero.

 Mapper.CreateMap<EventsAddEditViewModel, Event>(); Event thisEvent = _eventRepository.GetById( viewModel.Id ); if (thisEvent == null) { thisEvent = new Event(); } Mapper.Map( viewModel, thisEvent ); thisEvent.EventType = new EventType { Id = viewModel.EventTypeId }; ValidationResult result = _eventService.Save( thisEvent ); 
+5
source

The reason is that the object is not the one you received from NHibernate.

Either use this object, or if your real code is different from the previous one, then here is another approach ...

In your NHibernate code, did you try to execute session.Merge () or session.SaveOrUpdateCopy () or so instead of session.Save () or session.Update ()?

0
source

Source: https://habr.com/ru/post/1340730/


All Articles