The mistake in your mapping is that you use Appointment.Calendar
twice for two different relationships. That's not possible. You would need a second pair of FK and navigation properties in Appointment
(or map one relationship without inverse properties):
modelBuilder.Entity<Calendar>()
.HasMany(c => c.FreeSlots)
.WithRequired(c => c.Calendar1)
.HasForeignKey(c => c.Calendar1ID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Calendar>()
.HasMany(c => c.AppointmentsList)
.WithRequired(c => c.Calendar2)
.HasForeignKey(c => c.Calendar2ID)
.WillCascadeOnDelete(true);
(For at least one relationship you must disable cascading delete. Otherwise you'll end up with a multiple cascading delete exception.)
However, I have the feeling that you actually should have only one relationship and collection Calendar.Appointments
and a kind of status in Appointment
, like a bool IsFree
property. You could then always extract the free slots of a calendar entry with calendar.Appointments.Where(a => a.IsFree)
.