Paweł Iżycki

.NET developer, fan of automation and backend world.


One-To-One Entity Framework with Fluent Configuration

25 Jul 2017 » EntityFramework, .NET

Today I forgot how to model One-To-One relationship in EF. At the begining I thought it’s some missing feature in EF itself or I simply messed up my entity model configuration. I was wrong.

Loosing faith to understand what the hell is going I bothered my work college to look at it with fresh mind.

He’s real pro, so he carefully investigated my configuration and model generated by migration. He pointed my out that dependent entity should only have the ID of referenced entity (principal).

The following is correct One-To-One configuration for EF 6.1.3

public class Foo {
  public Guid Id { get; set; }
  public virtual Bar { get; set; }
}

public class Bar {
  public Guid FooId { get; set; }
  public virtual Foo { get; set; }
} 
// EntityTypeConfiguration<Foo>
HasKey(e => e.Id); // This is primary key of Foo entity.

// One-to-One relation
HasRequired(e => e.Bar)
   .WithRequiredPrincipal(e => e.Foo);
// EntityTypeConfiguration<Bar>
HasKey(e => e.FooId); // The primary key (and foreign key) is the referenced entity ID

In One-To-One relation both entities are required. This is enforced by EF. Such concept doesn’t exist in SQL as every One-To-One relationship is always left with one entity optional. In that case this is Bar entity.

Putting this simple as I can, Bar entity needs Foo to exists before its own creation.

You can read more about EF entity relationships on MSDN article: