I am trying to understand EF code first approach with two simple table student and course have PK and FK relation.
EF has generated following mapping in OnModelCreating
modelBuilder.Entity<Course>()
.HasMany(e => e.Students)
.WithRequired(e => e.Course)
.WillCascadeOnDelete(false);
In repository i have following method
public List<Course> GetCourses()
{
using (SampleDBContext ctx = new SampleDBContext())
{
return ctx.Courses.Include("Students").ToList();
}
}
Above method returns list of Course with list of student enrolled for each course(as using early-loading).
Then i removed PK-FK relationship from DB and also removed HasMany mapping mentioned in OnModelCreating even.
After that i tested GetCourses() method again and it is still returning list of student belonged to each course.
So i could not understand why we need to define entity relationship mapping in EF.
And also while defining navigation property- using virtual ICollection OR simple LIST does not have any impact. Is it good practice of using virtual ICollection?
public virtual ICollection<Student> Students { get; set; }
// OR
public List<Student> Students { get; set; }
Please help me understand- Why explicit mapping should do and how EF get navigation data even no PK-FK relation is defined in DB.
Note- I am using EF6(code first from DB)
Thanks,
@Paul