Configuring One-to-One Relationships
Explore how to configure one-to-one relationships between entities in Entity Framework Core. Understand default conventions, and learn to customize relationships using data annotations or the fluent API. Gain practical skills to set foreign keys, unique indexes, and navigate navigation properties ensuring correct relational mapping.
We'll cover the following...
Overview
In this lesson, we’ll look at the conventions between two entities that result in a one-to-one relationship between their corresponding tables in the database. We’ll also look at how to supplement these conventions using data annotations and the fluent API.
One-to-one relationships require a reference navigation property at both ends. A unique index is also introduced on the foreign key property to ensure only one dependent entity links to the principal entity.
Note: The commands in this lesson generate code and files. Through the terminal, we can navigate to these files by using relevant Linux commands such as
lsto view a list of files and directories,cdto change directories, andcatto view file contents. A SPA widget showing the updated project with the generated files is also available. Also, note that EF Core uses a timestamp within the generated file names. We represent these names withxxx.
Default conventions
By convention, EF Core identifies the dependent entity as the entity having a foreign key property. EF Core picks EmployeeId as the foreign key in this project because it matches the <navigation property name><principal key property name> pattern. Therefore, the one-to-one relationship is configured by default.
We’ll demonstrate configuring a ...