Updated on Kisan Patel
Problem:
How to Define multiple Foreign Key for the Same table in Entity Framework Code First.
Solution:
To achieve what you want you need to provide some additional configuration.Code First convention can identify bidirectional relationships, but not when there are multiple bidirectional relationships between two entities.
With Data Annotations, you will use an annotation called InverseProperty
.
Example:
public class City { public int ID { get; set; } public string CityName { get; set; } public virtual ICollectionStudents { get; set; } } public class Student { public int ID { get; set; } public string Name { get; set; } public int BirthCityID { get; set; } [ForeignKey("BirthCityID")] [InverseProperty("Students")] public virtual City BirthCity { get; set; } public int LivingCityID { get; set; } [ForeignKey("LivingCityID")] public virtual City LivingCity { get; set; } }