Configure One-to-One relationship using Fluent API in Entity Framework Core

Configure One-to-One relationship using Fluent API in Entity Framework Core

Here you will learn how to configure One-to-One relationship using Fluent API. But generally speaking, you don’t need Fluent API to do this as the EF Core Conventions will automatically create the One-to-One relationship between entities.

Let’s create 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; }
} 

Next configure the OnModelCreating method in the context class, as shown below.

public class CompanyContext : DbContext
{
    public DbSet<City> City { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {         optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
        }
    }

    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);
    }
}

Or, you can do the other way around like the code below:

modelBuilder.Entity<CityInformation>()
            .HasOne(e => e.City)
            .WithOne(e => e.CityInformation)
            .HasForeignKey<City>(e => e.CityInformationId);

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

one to one relationship fluent api

Understanding One-to-One Relationship creation by Fluent API

Let’s understand it step by step.

  • modelBuilder.Entity() starts configuring the City entity.
  • The HasOne(e => e.City) method specifies that the ‘City’ entity includes one ‘CityInformation’ reference property.
  • The .WithOne(e => e.CityInformation) configures the other end of the relationship, the ‘CityInformation’ 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

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.