Still on NHibernate...
Yesterday I was complaining about the way NHibernate persists entities that contain collection of components. After some discussions on the Forums, Karl suggested that I should call session.Flush after calling the Save(OrUpdate) method to force the generation of the collection of components maintained in the collection. This means that something along these lines should work:
- Open a session
- Begin transaction
- Insert into db by calling the Save(OrUpdate) method
- Flush the session by calling session.Flush
- //perform other work here
- Rollback or commit the transaction
Notice that I no longer call session.Flush after ending the transaction...After trying this approach, I can confirm that it does work. However, I still think that this is not intuitive and it really shouldn't work like this. When I persist an entity, I'm expecting that all of its depend objects are persisted too (persisted here means that the necessary insert commands are automatically generated and executed over the existing transaction). For instance, if I had to write SQL code to perform this operation, I'd do something like this:
- start transaction
- insert into main table
- insert into secondary table (ie, insert the components)
- //perform other work here (ie, write some code that tests the insertion)
- rollback the transaction
I guess that the main problem here is that NHibernate has its own way of persisting entities to the database and, most of the time, everything works out as expected. Unfortunately, that is not the case when an entity has a collection of components. And even though I really don't know much about NHibernate, I really can't see how the default behavior is the correct one in this kind of scenarios...