I am trying to define the following model where Appointment table has foreign key for Person, and the entities both have navigation properties to each other.
public class Appointment
{
public int AppointmentId { get; set; }
// Foreign Key property (this will be created in DB)
public int? PersonId { get; set; }
// Navigation property to Flatmate
public virtual Person Person { get; set; }
}
public class Person
{
public int PersonId { get; set; }
// Just navigation property. Don't want Person table to include foreign key (no need)
public virtual Appointment Appointment { get; set; }
}
I try to use fluent config:
modelBuilder.Entity<Appointment>()
.HasOptional(a => a.Person)
.WithOptionalDependent(p=> p.Appointment);
But I get an exception that its missing a column (either Appointment_AppointmentId or Person_PersonId, depending on whether I use WithOptionalDependent or WithOptionalPrincipal).
Entity Framework doesn’t support this.
HasOptional().WithOptionalDependent()can work when both tables use the same key (PersonId == AppointmentId), but that’s not the situation you have. In order to ensure that one person doesn’t have multiple appointments, you’d need to make surePersonIdis unique in theAppointmenttable, and Entity Framework doesn’t support unique constraints.What you could do (without changing your database) is map this as a one-to-many relation, where one person can have multiple appointments, and create a helper property to return the one appointment:
Note that Entity Framework won’t understand the
Appointmentproperty, so you cannot use it in queries.