Reputation: 186
I have a PhoneBook class that has a list of PhoneNumber. Then I have another class "Account" that references PhoneNumber. This reference is nullable, so an account doesn't have to have a phone number.
I would like to be able to save the PhoneBook, have it save/update/delete all the phone numbers, AND if any of the phone numbers are deleted, I want to null out any accounts using this number. Everything is working except for the last part; if I delete a phone number that's in use it deletes the account too, which I do not want to happen, I just want it to clear it's reference. I'm sure it's just because my cascades or mappings are wrong, I just don't know what to set them to.
The actual code to save is relatively simple. Incidentally, if someone can tell me why I have to Merge in order to make sure phone numbers are deleted that would be awesome.
var session = SessionFactory.GetCurrentSession();
book = (PhoneBookDto) session.Merge(book);
session.SaveOrUpdate(book);
Current relevant mappings:
PhoneBook.hbm.xml
...
<bag cascade="all-delete-orphan" inverse="true" name="PhoneNumbers">
<key>
<column name="phone_book_id" />
</key>
<one-to-many class="DataLibrary.dto.PhoneNumberDto, DataLibrary" />
</bag>
...
PhoneNumber.hbm.xml
...
<many-to-one cascade="none" class="DataLibrary.dto.PhoneBookDto, DataLibrary" name="PhoneBook">
<column name="phone_book_id" />
</many-to-one>
...
Account.hbm.xml
...
<many-to-one cascade="none" class="DataLibrary.dto.PhoneNumberDto, DataLibrary" name="PhoneNumber">
<column name="phone_number_id" />
</many-to-one>
...
Thanks in advance!
edit:
Firo pointed me in the right direction, I had to set up a collection on PhoneNumber back to Account even though I don't really need it, and also set it as inverse=false:
<bag cascade="none" inverse="false" name="Accounts">
<key>
<column name="phone_number_id" />
</key>
<one-to-many class="DataLibrary.dto.AccountDto, DataLibrary" />
</bag>
When I did that, it worked. Is there any way to do this so I don't have to have an association on PhoneNumber to Account?
Upvotes: 1
Views: 1724
Reputation: 30813
"why I have to Merge in order to make sure phone numbers are deleted":
Either because you removed Phonenumbers out of changetracking (closed session with which the book was loaded) or because there is no Flush at the end while merge will immediatly flush the SaveOrUpdate will only add to the batch which is executed on next session.Flush().
"it deletes the account too"
maybe because of:
<bag cascade="all" class="Account" name="Accounts">
</bag>
Upvotes: 1