NHibernate and AutoMapper not playing nice: "a different object with the same identifier value was already"
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);开发者_Go百科
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.
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 );
The reason is that the object is not the one you got from NHibernate really.
Either use that object, or if your real code is different than above then here is another approach...
In your NHibernate code, did you try session.Merge() or session.SaveOrUpdateCopy() or so instead of session.Save() or session.Update() ?
精彩评论