NHibernate 和 AutoMapper 表现不佳:“已经存在具有相同标识符值的不同对象”
收到此错误: 具有相同标识符值的不同对象已经与会话关联:27,实体:xxx.Core.Event
基本上,我有从我的 poco 映射的视图模型,反之亦然。有问题的代码在这里:
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);
基本上我从数据库加载事件,然后将视图模型映射到该事件并保存。否则,视图上未显示的字段(例如 dateCreated)将无法正确保存。
NHibernate 和 AutoMapper 有什么办法可以在这方面发挥出色吗?
我正在使用 OnePerRequestBehavior 作为我的会话提供程序。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
保存时将相同的对象归还给 NHibernate。
为此,我们使用
Mapper.Map()
的不同重载。此外,当编译器可以找出类型时,就不需要指定它们。此外,
GetById()
可能会返回 null。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.原因是该对象并不是您真正从 NHibernate 获得的对象。
要么使用该对象,要么如果您的真实代码与上面不同,那么这里是另一种方法...
在您的 NHibernate 代码中,您是否尝试了 session.Merge() 或 session.SaveOrUpdateCopy() 等而不是 session.Save()或会话.Update() ?
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() ?