Mapping with one-to-zero-or-one


Mapping with one-to-zero-or-one

To configure One-to-Zero-or-One relationships between two entities, we will implement a one-to-Zero-or-One relationship between the following Student and StudentAddress entities.

A one-to-zero-or-one relationship happens when a primary key of one table becomes PK & FK in another table in a relational database such as SQL Server. So, we need to configure the above entities so that EF creates the Students and StudentAddresses tables in the DB and makes the StudentId column in the Student table as PrimaryKey (PK), StudentAddressId column in the StudentAddresses table as PK, and ForeignKey (FK) both.

Configure One-to-Zero-or-One Relationship using Data Annotation Attributes

To establish a one-to-zero-or-one relationship, we will apply data annotation attributes to the Student and StudentAddress entities.

The Student entity follows the default code-first convention as it includes the StudentId property, which will be the fundamental property. So, we don't need to apply any attributes to it because EF will make the StudentId column a PrimaryKey in the Students table in the database.

For the StudentAddress entity, we need to configure the StudentAddressId as PK & FK. The StudentAddressId property follows the default convention for the primary key. So, we don't need to apply any attribute for PK. However, we also need to make it a foreign key that points to StudentId of the Student entity. So, apply [ForeignKey("Student")] on the StudentAddressId property, which will make it a foreign key for the Student entity

Configure a One-to-Zero-or-One relationship using Fluent API

We will use Fluent API to configure a one-to-zero-or-one relationship between the Student and StudentAddress entities.

Configure a One-to-One relationship using Fluent API

We can configure a one-to-One relationship between entities using Fluent API where both ends are required. The Student entity object must include the StudentAddress entity object, and the StudentAddress entity must consist of the Student entity object to save it.

3