views:

226

answers:

1

Hi,

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?

A: 

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.

Jamie Ide
Thanks for the quick reply. What would happen if I had a large number of appointments that have this outcome set, including appointments not in the current session? Would I have to perform a batch update - should I use NHibernate for this or create a stored procedure to update them?
Matt
See this post on batch updates with NHibernate:http://stackoverflow.com/questions/982295/saving-1000-records-to-the-database-at-a-timeI personally wouldn't run a batch update using NHibernate and would resort to native SQL instead.
Programming Hero