I am getting a foreign key error when trying (probably to do too much) within a single SaveChanges.
Basically I have following 3 poco entities like so.
public class ClinicianAvailability
{
public int ClinicianAvailabilityId { get; set; }
}
public class SurgicalBooking
{
public int SurgicalBookingId
public int? ClinicianAvailabilityId { get; set; }
public bool IsAdhoc { get; set; }
public virtual TheatreBooking TheatreBooking { get; set; }
public virtual ClinicianAvailability ClinicianAvailability { get; set; }
}
public class TheatreBooking
{
public int TheatreBookingId {get;set;}
public virtual SurgicalBooking SurgicalBooking { get; set; }
public virtual ClinicianAvailability ClinicianAvailability { get; private set; }
}
I am basically trying to delete a ClinicianAvailability which has a Foreign Key on the SurgicalBooking. But at the sametime trying to set a new TheatreBooking on the SurgicalBooking.
Like this:
var entity = _clinicianAvailabilityRepository.Find(resourceAvailabilityId);
var surgStub = surgicalBookingRepository.CreateStub(bookingData.ScheduleId);
surgStub.IsAdhoc = true;
surgStub.ClinicianAvailabilityId = null;
surgicalBookingRepository.SetModified(surgStub, new Expression<Func<SurgicalBooking, object>>[] { x => x.IsAdhoc, x => x.ClinicianAvailabilityId });
theatreBookingRepository.Add( new TheatreBooking
{
TheatreBooking Id = theatreBookingRepository.GetNewTempKey(),
TheatreId = associatedTheatreId.Value,
SurgicalBooking = surgStub
});
theatreBookingRepository.Add(TheatreBooking);
_clinicianAvailabilityRepository.Remove(entity);
_clinicianAvailabilityRepository.UnitOfWork.SaveChanges();
So basically after doing this I get a foreign key error on the SurgicalBooking foreign key of ClinicianAvailabilityId. If I take out the adding of the TheatreBooking, it goes in the right order by updating Surgical Booking and then deleting. But with Adding the Theatre Booking it tries to do the delete first and then fails. Any help with this? I've tried to simplify this as much as possible but it's a bit complicated. I'm trying to not do multiple save changes or put it all inside a single transaction because it would be a lot of rework to change all this code.
I have looked in the ChangeTracker and all the items seem to be there in the right order, but it doesn't do it in that order.