We can configure Entity Framework Core One-to-One Relationship by the use of Fluent API. The One-to-One Relationship is established by using the HasOne – WithOne pattern. Note that we can also create this relationship by using EF Core Conventions.
Let’s create Entity Framework Core One-to-One relationship between City and CityInformation entities using Fluent API.
The 2 entity classes are:
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public int CityInformationId { get; set; }
public CityInformation CityInformation { get; set; }
}
public class CityInformation
{
public int Id { get; set; }
public int Population { get; set; }
public string OtherName { get; set; }
public string MayorName { get; set; }
public City City { get; set; }
}
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.
public class CountryContext: DbContext
{
public DbSet<City> City { get; set; }
public DbSet<CityInformation> CityInformation { get; set; }
public CountryContext(DbContextOptions<CountryContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Write Fluent API configurations here
modelBuilder.Entity<City>()
.HasOne(e => e.CityInformation)
.WithOne(e => e.City)
.HasForeignKey<City>(e => e.CityInformationId);
}
}
In the above code we 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 we did in the below code.
modelBuilder.Entity<CityInformation>()
.HasOne(e => e.City)
.WithOne(e => e.CityInformation)
.HasForeignKey<City>(e => e.CityInformationId);
On doing the EF Core Migrations the foreign key i.e. one-to-one relationship is created which is shown in the below image:
Let’s understand it in step by step.
Download the source code: