Here you will learn how to configure One-to-One Relationship using Fluent API. Note that you can also create this relationship by using EF Core Conventions. The One-to-One Relationship is established by using the HasOne – WithOne pattern.

Let’s create One-to-One relationship between City and CityInformation entities using Fluent API.

The 2 entity classes are:

The City entity has a Reference Navigation Property called CityInformation.

public CityInformation CityInformation { get; set; }

Similary the CityInformation entity has a Reference Navigation Property called City

public City City { get; set; }

Next configure the OnModelCreating method in the DB Context Class of Entity Framework Core as shown below.

In the above code I have used the HasOne – WithOne pattern to create One-to-One Relationship between City & CityInformation entities.

You can also create the same relationship the other way around like what I did in the below code.

On doing the EF Core Migrations the foreign key (one-to-one relationship) is created which is shown in the below image:

Understanding One-to-One Relationship creation by Fluent API

Let’s understand it in step by step.

modelBuilder.Entity() starts configuring the City entity.

starts configuring the entity. The HasOne(e => e.City) method specifies that the City entity includes one CityInformation reference navigation property.

method specifies that the entity includes one reference navigation property. The .WithOne(e => e.CityInformation) configures the other end of the relationship, i.e. the CityInformation entity. It specifies that the ‘CityInformation’ entity includes a reference navigation property of ‘City’ type.

configures the other end of the relationship, i.e. the entity. It specifies that the ‘CityInformation’ entity includes a reference navigation property of ‘City’ type. The .HasForeignKey(e => e.CityInformationId) specifies the foreign key property name which is the CityInformationId column.

Download the source code:

DOWNLOAD