Configure One to One Relationship in Entity Framework Core

Entity Framework Core will create a one-to-one relationship when both entities involved in the relationship have a navigational property of the other and the dependant entity contains a foreign key property of the principal entity. Consider the following example.

 public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }      
        public CustomerAddress CustomerAddress { get; set; }

    }
 public class CustomerAddress
    {
        public int Id { get; set; }     
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public int CustomerId { get; set; }
        public Customer Customer { get; set; }
    }

Here, the Customer entity contains a navigational property of the CustomerAddress entity and the CustomerAddress entity contains a navigational property and a foreign key property of the Customer entity. This results in a one-to-one relationship as EF Core creates a not null foreign key with a unique constraint for the CustomerId property in the CustomerAddress table.

The foreign property name must follow Entity Framework Core conventions to recognize it as the foreign key property by Entity Framework Core. If it doesn't follow the naming conventions of the foreign key property, you will get an error similar to the following

The dependent side could not be determined for the one-to-one relationship between 
'Customer.CustomerAddress' and 'CustomerAddress.Customer'. To identify the dependent
side of the relationship, configure the foreign key property. If these navigations should not
be part of the same relationship, configure them independently via
separate method chains in 'OnModelCreating'.

This relationship can also be configured using Fluent API as given below.

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>()
        .HasOne(a => a.CustomerAddress).WithOne(b => b.Customer)
        .HasForeignKey<CustomerAddress>(e => e.CustomerId);
        }

 


Search