简体   繁体   English

在 Asp.Net 中使用 NHibernate 更新实体

[英]Updating an entity with NHibernate in Asp.Net

What's the recommended way of updating an entity?更新实体的推荐方法是什么? So far, I figured out two ways:到目前为止,我想出了两种方法:

  1. Just create a new entity with the existing Id and updated property values, and use session.SaveOrUpdate()只需使用现有 Id 和更新的属性值创建一个新实体,然后使用 session.SaveOrUpdate()
  2. Use a DTO, retrieve the existing entity using session.Load(dto.Id), assign new vaues from the dto, then save.使用 DTO,使用 session.Load(dto.Id) 检索现有实体,从 dto 分配新值,然后保存。

No1 requires much less effort, but sometimes I'm getting an exception: "a different object with the same identifier value was already associated with the session". No1 需要的工作少得多,但有时我会遇到异常:“具有相同标识符值的不同 object 已与会话相关联”。 Is there a simple way around that?有没有简单的解决方法?

No2 might require an extra trip to the DB I guess?我猜 2 号可能需要额外前往数据库?

Sorry if that's been answered already, just couldn't find the answer.对不起,如果已经回答了,只是找不到答案。

Thanks ulu谢谢乌鲁

Your second option with DTOs is my preferred way.您对 DTO 的第二个选择是我的首选方式。 Your DTOs should be specific to the screen (Google Screen Bound DTOs) so that the screen and your domain can change independently of one another.您的 DTO 应该特定于屏幕(Google Screen Bound DTO),以便屏幕和您的域可以相互独立地更改。

It also won't add an extra trip to the db since #1 would require a disconnected entity which would have to be reconnected (which triggers a select) after the fact.它也不会向数据库添加额外的行程,因为#1 需要一个断开连接的实体,该实体必须在事后重新连接(触发选择)。 Worrying about one extra select also smells strongly of premature optimization.担心一个额外的 select 也有强烈的过早优化的味道。

In terms of converting from domain to DTO I'd recommend looking at AutoMapper.在从域转换为 DTO 方面,我建议查看 AutoMapper。

To use No1 you could try and Evict the object from nHibernates session. This will get rid of the error about the object already being in the session.要使用 No1,您可以尝试从 nHibernates session 中驱逐 object。这将消除关于 object 已经在 session 中的错误。

I would recommend approach number 2. Especially if you want to add any sort of optomistic locking.我会推荐方法 2。特别是如果你想添加任何类型的光学锁定。 In many cases a single extra hit to the db won't be that expensive.在许多情况下,对数据库的一次额外点击不会那么昂贵。

Edit编辑

To check if a entity already exists in the session you can use the Contains(obj) method on the Session instance.要检查 session 中是否已存在实体,您可以在 Session 实例上使用 Contains(obj) 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM