views:

52

answers:

2

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

A: 

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.

lalit
+1  A: 

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)

Diego Mijelshon
While I'm finding that Load is going to the DB (maybe something else I need to address, lazy does = true the Product mapping). This totally solves the main issue. Thanks
Christopherous 5000
Lazy should almost NEVER be false; if it is, there's your issue.
Diego Mijelshon
right - I'm saying it's at the default (true)
Christopherous 5000