1

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

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
paul sim
  • 463
  • 2
  • 10
  • 23
  • You need to define the relations because you want to have them in your DB. This is the only way for the SQL Server to stop you from harming your data. Otherwise your DB will, with time, eventually become inconsistent. Relations guard you against yourself and other devs who will work on your project - How another dev or db admin will know that X requires Y which requires Z?. You may also take a look at [this](http://stackoverflow.com/questions/2317391/is-there-a-severe-performance-hit-for-using-foreign-keys-in-sql-server) discussion for the performance hit of non-indexed foreign keys. – Ognyan Dimitrov Aug 17 '15 at 06:41

1 Answers1

1

For configuring EF you have 3 option:

1) By Convention (Convention over configuration):

In this method EF tries to discover tables schema based on classes structures.

2) By Data Annotation:

In this method we could alter discovered configuration by adding attributes to classes or properties.

3) By Fluent API:

Exact same as Data Annotation method but by calling some configuration method instead of assigning attributes.

In your example EF already discovered your desired configuration by conviction. So your extra configuration (by Fluent API) useless. We use 2nd or 3rd method if EF fails to configure DB in a our desired form.

Also if you want EF generates proxy classes to perform lazy loading use virtual keyword. If not you could omit it.

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56