NHibernate 到现有对象的多对多映射

发布于 2024-09-25 15:40:58 字数 546 浏览 3 评论 0原文

我尝试创建的多对多关系遇到一些问题。目标是保存客户以及允许他们购买哪些产品。这些产品并不是客户独有的,在我们尝试将客户与它们关联之前,它们始终存在于数据库中。

我的关联映射当前看起来像...

<set name="AllowedProducts" table="Customer_AllowedProducts">
      <key column="CustomerId"></key>
      <many-to-many class="Product" column="ProductId"/>
</set>

如果我尝试保存客户,我会收到引用该产品的 NHibernate.TransientObjectException 。我知道我可以向集合中添加级联,但我从不想在保存客户时更新或保存产品,我们只想将客户映射到现有产品。

我应该注意到,我尝试保存的客户来自 Web 服务调用,因此不会引用先前已加载到会话中的产品。我想避免必须加载将映射到会话中的每个产品。

谢谢

I'm having some issues with a many-to-many relationship I am trying to create. The goal is to save a customer and which products they are allowed to purchase. The products are not unique to a customer and will ALWAYS exist in the database before we try to associate a customer to them.

My mapping for the association currently looks like...

<set name="AllowedProducts" table="Customer_AllowedProducts">
      <key column="CustomerId"></key>
      <many-to-many class="Product" column="ProductId"/>
</set>

If I try to save a Customer I get a NHibernate.TransientObjectException referencing the product. I understand that I could add cascade to the set, but I NEVER want to update or save a product when saving a customer, we only want to map a customer to existing products.

I should note that the customer I'm trying to save is coming in from a webservice call and therefore does not reference products that have been previously loaded into the session. I would like to avoid have to load every product that will be mapped into the session.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

放赐 2024-10-02 15:40:58

您的代码应该如下所示:

customer.AllowedProducts.Add(session.Load<Product>(productIdFromTheRequest));

而不是您可能正在做的事情:

customer.AllowedProducts.Add(new Product {Id = productIdFromTheRequest});

值得注意的是 Load never 进入数据库;它只返回一个代理(或检索到的实例,如果当前会话中存在)

Your code should look like this:

customer.AllowedProducts.Add(session.Load<Product>(productIdFromTheRequest));

Instead of what you are probably doing:

customer.AllowedProducts.Add(new Product {Id = productIdFromTheRequest});

It's worth noting that Load never goes to the DB; it just returns a proxy (or a retrieved instance, if one is present in the current session)

酒中人 2024-10-02 15:40:58

您必须将产品附加到休眠会话,以便它们成为托管实体。据我所知,没有其他出路。

You will have to attach the product to hibernate session so that they become managed entity. As far as I know, there is no other way out.

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