ZedBee
ZedBee

Reputation: 2378

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

Upvotes: 3

Views: 3098

Answers (2)

Aiska Hendra
Aiska Hendra

Reputation: 145

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; }
}

Upvotes: 1

Saber Amani
Saber Amani

Reputation: 6489

Just try this :

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

Hope this help.

Upvotes: 6

Related Questions