This project is read-only.

How to properly remove / add records using a session?

Topics: Core, General, Troubleshooting, Writing modules
Mar 6, 2013 at 8:28 AM
Something that still isn't clear for me:

If you have, for example, the following structure:

BRecord B;
CRecord C;
DRecord[] DList;
CRecord CRecord;

And I do this:
  • Create a new ARecord instance 'A'
  • Create a new BRecord instance and assign it to 'A.B'
  • Create a new CRecord instance and assign it to 'A.B.C'
  • Create multiple new DRecord instances and add it to the list 'A.B.C.DList'
What do I need to do to save all these new records?

Just 'SaveOrUpdate' A and it'll save all the other records as well?
If not, in what order should I be saving the records?

Also, do I need to set the 'DRecord.CRecord' property to point to its parent myself? Or is this done by itself?
If I need to do this myself, do I need to do it before or after saving the 'A.B.C' record?
What if I remove an item from the list 'A.B.C.DList'?
Do I need to just remove the item from the list and save 'A.B.C'? Or do I also need to remove the DRecord instance myself?

Any aid is GREATLY appreciated - our existing code works but since we were never sure how these things worked I think we're doing too many saves (and cluttering our code because of those)
Mar 6, 2013 at 9:57 AM
Mar 6, 2013 at 10:44 AM
The way I understand it, the objects are considered transient when you first instantiate them. Basically meaning that they aren't registered or known about by the session. So, you'll need to associate all of them by passing to SaveOrUpdate if they were not retrieved from the session in the first place.
Mar 6, 2013 at 10:46 AM
Thanks for the quick reply.

Do you also know the answer to my questions regarding adding to / removing from lists?
Mar 6, 2013 at 10:48 AM
Also, Orchard has some built in conventions that can figure out the association mappings in your example. You will need to set the parent property manually as you mentioned though. Typically (as in this case) this parent property is used to govern the one-to-many mappings when using NHibernate. The order that you call SaveOrUpdate on these objects shouldn't matter as long as they are all registered with the session before you call Flush or before the transaction automatically flushes for you.
Mar 6, 2013 at 10:51 AM
So it would be okay to SaveOrUpdate A first when it has B assigned with an 'unsaved' instance since the order doesn't matter?
Mar 6, 2013 at 10:53 AM
Yep, that's totally ok. If you forgot to SaveOrUpdate B later though, you would get a Transient object sort of exception from nhibernate when it tries to commit.
Mar 6, 2013 at 10:54 AM
Well tyvm for this info, I think this cleared things up nicely for us :)