Description
Hi! I seem to be running into an issue where orphaned records are not getting deleted, and would be very grateful for any advice.
We have a Medication class. Each Medication has a Frequency property. This relationship is described in the mapping as follows:
public class MedicationMap : ClassMap<Medication>
{
public MedicationMap()
{
Table("Medication");
References(x => x.Frequency)
.Column("FrequencyId")
.Cascade.DeleteOrphan()
.Cascade.SaveOrUpdate();
}
}
There are 4 possible Frequency types. They all inherit from a BaseFrequency abstract class that has a few properties, and there are different properties on the 4 derived classes.
In the MSSQL database, the Medication table has a FrequencyId column, which is a Foreign Key to the Frequency table.
The user can edit Medications, and as a part of this they can also edit the frequency, including switching it to a new type.
Because of this, we can't simply update properties on the existing Frequency record and call it a day. Instead, during the update of a medication we must set its frequency to a new frequency which has all the edited properties the user entered. After that, we call SaveOrUpdate on the existingMedication:
existingMedication.Frequency = newFrequency;
Transact(() => Session.SaveOrUpdate(existingMedication));
This successfully creates a new record in the Frequency table, and correctly update the Medication's FrequencyId value to the newly created Frequency record. However, the old Frequency record is not deleted from the Frequency table, even though there are now no Medications that refer to its FrequencyId.
I have tried setting Cascade to Cascade.AllDeleteOrphans(), but that has the same effect.
Am I doing something wrong in my mapping? Does NHibernate not have enough information available to know for sure if the record is orphaned?