如何保存 NHibernate 会话中已存在的瞬态对象?
我有一个包含 产品
列表的 Store
:
var store = new Store();
store.Products.Add(new Product{ Id = 1, Name = "Apples" };
store.Products.Add(new Product{ Id = 2, Name = "Oranges" };
Database.Save(store);
现在,我想编辑其中一个 产品
,但使用瞬态实体。例如,这将是来自网络浏览器的数据:
// this is what I get from the web browser, this product should
// edit the one that's already in the database that has the same Id
var product = new Product{ Id = 2, Name = "Mandarin Oranges" };
store.Products.Add(product);
Database.Save(store);
但是,尝试这样做会出现错误:
具有相同标识符值的不同对象已与会话关联
原因是 store.Products
集合已包含具有相同 Id 的实体。我该如何解决这个问题?
I have a Store
that contains a list of Products
:
var store = new Store();
store.Products.Add(new Product{ Id = 1, Name = "Apples" };
store.Products.Add(new Product{ Id = 2, Name = "Oranges" };
Database.Save(store);
Now, I want to edit one of the Products
, but with a transient entity. This will be, for example, data from a web browser:
// this is what I get from the web browser, this product should
// edit the one that's already in the database that has the same Id
var product = new Product{ Id = 2, Name = "Mandarin Oranges" };
store.Products.Add(product);
Database.Save(store);
However, trying to do it this way gives me an error:
a different object with the same identifier value was already associated with the session
The reason is because the store.Products
collection already contains an entity with the same Id. How do I get around this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
而不是尝试合并瞬态实例。为什么不从实际实例开始...只需通过 id 获取产品,更新字段,然后提交。
或者合并方式...
Instead of trying to merge the transient instance. Why not start with the actual instance...simply get the product by id, update the fields, and commit.
or the merge way...
在没有更多上下文的情况下,我对这种情况不是 100% 肯定,但会话合并可能会起作用。
http://ayende.com/博客/archive/2009/11/08/nhibernate-ndash-cross-session-operations.aspx
I'm not 100% positive in this case without more context, but a session merge might work.
http://ayende.com/Blog/archive/2009/11/08/nhibernate-ndash-cross-session-operations.aspx
也许你应该调用 Database.SaveOrUpdate(store);而不是纯粹的 Save(store) ?
Maybe You should call Database.SaveOrUpdate(store); instead of pure Save(store) ?