I am working on a group project where an one on one relation in Entity framework is defined like this
builder.Entity<ApprovedAppointment>()
.HasOne(aa => aa.Appointment)
.WithOne(a => a.ApprovedAppointment)
.HasForeignKey<ApprovedAppointment>(a => a.ApprovedAppointmentId);
using fluent api. In the database the appointment primary key is the same as approvedAppointment primary key. For example, if appointmentId 5 is the first appointment to be accepted then the approvedAppointmentId is also 5 even though there are no other approvedAppointments inserted yet. Is this normal behaviour? Does anyone know why it works like this?
CodePudding user response:
Yes, this the default mapping behaviour because you are pointing the FK at the PK of the table. You could remove the .HasForeignKey()
altogether in that configuration.
The HasForeignkey()
is available in EF Core to allow you to nominate a configured one-to-one relationship key in either of the tables to point at the PK of the other.
For example, you could put an "AppointmentId" in your ApprovedAppointment table, or an "ApprovedAppointmentId" in your Appointment table then map the ForeignKey accordingly:
.HasForeignKey<ApprovedAppointment>(aa => aa.AppointmentId);
or
.HasForeignKey<Appointment>(a => a.ApprovedAppointmentId);
respectively.
This would allow Appointment to have an AppointmentId of 5, while ApprovedAppointment's ApprovedAppointmentId is 1 or 2, but contains an AppointmentId FK of 5 to reference back to the Appointment.
Typically in a 1-to-1 relationship the two tables would just share the same PK to ensure the relationship is 1-to-1. With the alternate FK designated you are mapping either a 1-to-many or many-to-1 relationship that EF will enforce as 1-to-1. I'm not sure if EF Code First will set up a unique constraint on the FK column, but if not, you should add one to enforce it at a data level.