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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.