0

I've been reading and viewing a lot of resources regarding EF, but -- at times -- I see some examples leaving out a foreign key id of a specific instance. Other times, they put it in. What are the implications of leaving it in or taking it out?

For example:

public class Student
{
  public int TeacherID { get; set; }
  [Required]
  public Teacher Teacher { get; set; }
}

public class Teacher
{
  public virtual List<Student> Students { get; set; }
}

vs.

public class Student
{
  [Required]
  public Teacher Teacher { get; set; }
}

public class Teacher
{
  public virtual List<Student> Students { get; set; }
}
Trecius Veil
  • 121
  • 8
  • Teacher still needs a key. In the second FK scenario, EF will automatically create a FK called Teacher_Id. – Steve Greene Feb 15 '16 at 19:04
  • when leaving the key out, you lose the control over it. however, EF will always create an FK to match navigation properties, as these otherwise will not be accessible – DevilSuichiro Feb 15 '16 at 19:06
  • The database table still needs a foreign key column. The implication of leaving it out of your EF model is that it makes it more difficult and error prone for EF to determine relationships. For this reason, I almost always use them. – danludwig Feb 15 '16 at 19:08
  • Thank you for the quick answers, all! It makes sense. – Trecius Veil Feb 15 '16 at 19:09

1 Answers1

0

The tables and entities always need primary keys when used with EF. With regards to foreign keys - the dependent table in the database still needs the foreign key but the corresponding entity does not have to have the property for the foreign key column. If you don't include foreign key properties in your model you will end up having Independent Associations. This post describes the difference between Independent Associations and Foreign Key Associations.

Community
  • 1
  • 1
Pawel
  • 31,342
  • 4
  • 73
  • 104