3
votes

I have a table of Appointments and a table of AppointmentOutcomes. On my Appointments table I have an OutcomeID field which has a foreign key to AppointmentOutcomes. My Fluent NHibernate mappings look as follows;

        Table("Appointments");
        Not.LazyLoad();
        Id(c => c.ID).GeneratedBy.Assigned();
        Map(c => c.Subject);
        Map(c => c.StartTime);
        References(c => c.Outcome, "OutcomeID");


        Table("AppointmentOutcomes");
        Not.LazyLoad();
        Id(c => c.ID).GeneratedBy.Assigned();
        Map(c => c.Description);

Using NHibernate, if I delete an AppointmentOutcome an exception is thrown because the foreign key is invalid. What I would like to happen is that deleting an AppointmentOutcome would automatically set the OutcomeID of any Appointments that reference the AppointmentOutcome to NULL.

Is this possible using Fluent NHibernate?

1

1 Answers

0
votes

You need to set the Outcome reference to null on the Appointment object when you delete an Outcome.

using (var txn = session.BeginTransaction())
{
    myAppointment.Outcome = null;
    session.Delete(outcome);
    txn.Commit();
}

You have the relationship mapped as one-to-many Outcome-to-Appointment(one outcome can be linked to multiple appointments). If an Outcome can be linked to multiple appointments then you would need to de-reference Outcome on all of them (or set cascading delete) before deleting the Outcome.