I would suggest you look at this problem from the perspective of NHibernate. And not from a relational database view. Let me begin with what I feel like you should do.
var customer = session.Load<Customer>(3); var order = session.Load<Order>(1); order.Customer = customer;
Now order.Customer.CustomerID will return 3.
As suggested by Serkan, it is better and more advisable to work with objects instead of primary keys.
In addition, there really should not be any impact on performance. Nhibernate can proxy many associations if classes have virtual public methods. Because of this, as long as you request only the client Id, it will not generate a separate SQL query. An identifier already exists with the proxy object.
Regarding the initial question, I have a hunch. NHibernate dynamically generates an SQL query to update and insert. This case has an update here. You have explicitly set the CustomerID property to 3. But the Customer property of the order object still points to the customer object with Id 1. Thus, when NHibernate generates an SQL query, it tries to set the value first to 1, as you requested it to. Then it also sees that the Client is still pointing to the old object, so the reset property of the CustomerId is 1. I think NHibernate gets confused with double mappings.
There are two things you can do. First enable the show_sql property in your NHibernate configuration.
<nhibernate> ... <add key="hibernate.show_sql" value="true" /> </nhibernate>
Verify that sql is generated when the order is saved. This will better explain the situation.
Secondly, after saving the order, session.Refresh(order); You can read about the Refresh () method here . Its end to the end of section 9.2. It will reload the order object with the new values ββfrom the database. Calling order.CustomerID should show what value you saved in the database.
source share