如何保存 NHibernate 会话中已存在的瞬态对象?

发布于 2024-08-29 17:38:56 字数 731 浏览 5 评论 0原文

我有一个包含 产品 列表的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒儿 2024-09-05 17:38:56

而不是尝试合并瞬态实例。为什么不从实际实例开始...只需通过 id 获取产品,更新字段,然后提交。

var product = session.Get<Product>(2);
product.Name = "Mandarin Oranges";
tx.Commit();

或者合并方式...

var product = new Product{ Id = 2, Name = "Mandarin Oranges" };
var mergedProduct = (Product) session.Merge(product);
tx.Commit();

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.

var product = session.Get<Product>(2);
product.Name = "Mandarin Oranges";
tx.Commit();

or the merge way...

var product = new Product{ Id = 2, Name = "Mandarin Oranges" };
var mergedProduct = (Product) session.Merge(product);
tx.Commit();
嘿哥们儿 2024-09-05 17:38:56

在没有更多上下文的情况下,我对这种情况不是 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

时光瘦了 2024-09-05 17:38:56

也许你应该调用 Database.SaveOrUpdate(store);而不是纯粹的 Save(store) ?

Maybe You should call Database.SaveOrUpdate(store); instead of pure Save(store) ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文