Defining multiple Foreign Key for the Same table in Entity Framework Code First

后端 未结 2 1313
陌清茗
陌清茗 2020-11-28 04:18

I have two entities in my MVC application and I populated the database with Entity Framework 6 Code First approach. There are two city id in the Student entity; one of them

2条回答
  •  囚心锁ツ
    2020-11-28 04:30

    Sheesh. It's been a long day. There's actually a very big, glaring problem with your code, actually, that I completely missed when I commented.

    The problem is that you're using a single collection of students on City. What's actually happening here is that EF can't decide which foreign key it should actually map that collection to, so it creates another foreign key specifically to track that relationship. Then, in effect you have no navigation properties for the collections of students derived from BirthCity and LivingCity.

    For this, you have to drop down to fluent configuration, as there's no way to configure this properly using just data annotations. You'll also need an additional collection of students so you can track both relationships:

    public class City
    {
        ...
    
        public virtual ICollection BirthCityStudents { get; set; }
        public virtual ICollection LivingCityStudents { get; set; }
    }
    

    Then, for Student:

    public class Student
    {
        ...
    
        public class StudentMapping : EntityTypeConfiguration
        {
            public StudentMapping()
            {
                HasRequired(m => m.BirthCity).WithMany(m => m.BirthCityStudents);
                HasRequired(m => m.LivingCity).WithMany(m => m.LivingCityStudents);
            }
        }
    }
    

    And finally in your context:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new Student.StudentMapping());
    }
    

提交回复
热议问题