开发者

NHibernate many-to-many mapping to existing objects

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 pr开发者_JAVA百科oduct 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


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜