NHibernate 到现有对象的多对多映射
我尝试创建的多对多关系遇到一些问题。目标是保存客户以及允许他们购买哪些产品。这些产品并不是客户独有的,在我们尝试将客户与它们关联之前,它们始终存在于数据库中。
我的关联映射当前看起来像...
<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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码应该如下所示:
而不是您可能正在做的事情:
值得注意的是
Load
never 进入数据库;它只返回一个代理(或检索到的实例,如果当前会话中存在)Your code should look like this:
Instead of what you are probably doing:
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)您必须将产品附加到休眠会话,以便它们成为托管实体。据我所知,没有其他出路。
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.