To configure One-to-Many relationships between two entities (domain classes) in Entity Framework 6. x using the code-first approach, configure a one-to-many relationship between the following Student and Grade entities where there can be many students in one Grade.
The one-to-many relationship can be configured in the following ways.
There are certain conventions in Entity Framework that, if followed in entity classes (domain classes), will automatically result in a one-to-many relationship between two tables in the database. You don't need to configure anything else.
We want to establish a one-to-many relationship between the Student and Grade entities where many students are associated with one Grade. It means that each Student entity points to a Grade, and this can be achieved by including a reference navigation property of type Grade in the Student entity class.
Another convention is to include a collection navigation property in the principal entity.
Including navigation properties at both ends will also result in a one-to-many relationship.
A fully defined relationship at both ends will create a one-to-many relationship.
Generally, you don't need to configure the one-to-many relationship in the entity framework because one-to-many relationship conventions cover all combinations. However, you may configure connections using Fluent API in one place to make it more maintainable.
Here, we will learn to configure a Many-to-Many relationship between the Student and Course entity classes. Students can join multiple courses, and numerous students can join one Course.
EF 6 includes default conventions for many-to-many relationships, and you need to include a collection navigation property at both ends. For example, the Student class should have a collection navigation property of Course type. The Course class should have a collection navigation property of Student type to create a many-to-many relationship without any configuration.
As you have seen above, the default convention for many-to-many relationships creates a joining table with the default naming conventions. Use Fluent API to customize a joining table name and column names.