Configure One-to-Many Relationships in EF


Configure One-to-Many Relationships in EF

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.

  1. By following Conventions
  2. By using Fluent API Configurations

Conventions for One-to-Many Relationships

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.

    Convention 1

    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.

    Convention 2

    Another convention is to include a collection navigation property in the principal entity.

    Convention 3

    Including navigation properties at both ends will also result in a one-to-many relationship.

    Convention 4

    A fully defined relationship at both ends will create a one-to-many relationship.

Configure a One-to-Many Relationship using Fluent API

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.

Configure Many-to-Many Relationships in Code-First

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.

Many-to-Many Relationship by Following Conventions

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.

Configure a Many-to-Many Relationship using Fluent API

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.

3