简体   繁体   中英

Why is there duplication of references in code-first EntityFramework?

In learning the code-first EntityFramework methodology, I don't understand why you need "duplicate" references between two data sets, ie a Navigation Property as well as an explicitly defined foreign key.

For example, an "Enrollment" has a one-to-one relationship with a "Course" and a "Student". In the student's model class, you define a navigation property like so:

public virtual ICollection<Enrollment> Enrollments { get; set; }

This will create a column for foreign keys to Student in the Enrollments table if you do a migration.

But in the "Enrollment" class, you also have a property representing the Student's foreign key like so:

public int StudentID { get; set; }

So my question is: what is the purpose of defining this foreign-key relationship on both ends? I have seen it done where only the Navigation Property is defined on one end, and also where the relationship is only defined on the other end. What is the reason for both?

The navigation property allows you to access the collection of referenced entities when you query the entity.

The single ID property is the reference to the column that actually holds the value of the foreign key reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM