同一个表的EF Code First Duplicate Foreign Key

时间:2013-01-17 20:31:26

标签: c# entity-framework ef-code-first

我一直在阅读有关EF Code First生成重复外键的SO帖子,并尝试将解决方案应用于我的代码但无法修复我的代码。

这是我的课程

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

这会在appointments表中生成两个外键,即SCHEDULEIDSchedule_Id1

如何告诉EF不要创建Schedule_Id1

2 个答案:

答案 0 :(得分:6)

试试这个:

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

希望得到这个帮助。

答案 1 :(得分:1)

您可以在属性约会

中使用InverseProperty数据注释
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; }
}