Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First Duplicate Foreign Key for same table

I have been reading SO posts about EF Code First generating duplicate foreign keys and tried to apply the solution to my code but unable to fix my code.

Here are my classes

 public class Schedule
{
    public int Id { get; set; }
    public ICollection<Appointment> Appointments { get; set; }
}

public class Appointment
{
    public int Id { get; set; }
    public Schedule Schedule { get; set; }
}

public class ScheduleConfiguration : EntityTypeConfiguration<Schedule>
{
    public ScheduleConfiguration()
    {
        HasKey(s => s.Id);
        Property(s => s.Id).HasColumnName("SCHEDULEID");            
        ToTable("SCHEDULES");
    }        
}

public class AppointmentConfiguration : EntityTypeConfiguration<Appointment>
{
    public AppointmentConfiguration()
    {
        HasKey(a => a.Id);
        Property(a => a.Id).HasColumnName("APPOINTMENTID");            
        HasRequired(a => a.Schedule).WithMany().Map(x => x.MapKey("SCHEDULEID"));
        ToTable("APPOINTMENTS");
    }
}

This is generating two foreign keys in appointments table namely SCHEDULEID and Schedule_Id1.

How can I tell EF not to create Schedule_Id1

like image 875
ZedBee Avatar asked May 10 '26 21:05

ZedBee


2 Answers

Just try this :

HasRequired(a => a.Schedule).WithMany(x=> x.Appointment).Map(x => x.MapKey("SCHEDULEID"));

Hope this help.

like image 53
saber Avatar answered May 12 '26 10:05

saber


You can use InverseProperty data annotation in property Appointments

public class Schedule
{
    public int Id { get; set; }
    [InverseProperty("Schedule")]
    public virtual ICollection<Appointment> Appointments { get; set; }
}

public class Appointment
{
    public int Id { get; set; }
    public Schedule Schedule { get; set; }
}
like image 27
Aiska Hendra Avatar answered May 12 '26 11:05

Aiska Hendra