It's a (self-referencing) many-to-many relationship: A grade can have many eligible grades and a grade can be the eligible grade for many other grades. You can think of it as if the Grade
entity had another (hidden) collection, like:
public class Grade
{
public GUID GradeId { get; set; }
public string GradeTitle { get; set; }
public virtual ICollection<Grade> EligibleGrades { get; set; }
public virtual ICollection<Grade> GradesThisIsAnEligibleGradeFor { get; set; }
}
The name is so ugly, we just remove the collection again. But you still have to tell EF that the relationship is many-to-many. If the Code-First model discovery sees only one collection it always assumes a one-to-many relationship (with a foreign key in TBLGRADES
table that doesn't exist). You must override the default conventions by using Fluent API in order to create a many-to-many relationship instead:
modelBuilder.Entity<Grade>()
.HasMany(g => g.EligibleGrades)
.WithMany() // <- parameterless because there's no 2nd (inverse) collection
.Map(m =>
{
m.ToTable("TBLGRADESRELATIONSHIPS");
m.MapLeftKey("GRADEID");
m.MapRightKey("ELIGIBLEGRADEID");
});
The last code snippet in your question should work now with this mapping and give exactly the result you expect.