简体   繁体   中英

Fluent NHibernate - Set reference key columns to null

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM