This short blog post serves as remainder how to create one-to-one relationship in Entity Framework code-first with fluent mapping. Every time I have to create a model with this relationship I google for code sample (I tend to forget things like this quite often), and only samples I could find are just too complex and the answer how to do it is hidden somewhere between 50.-60. line:)

Approach described here:

  • I wanted to have one to one relationship where both entities have foreign keys of each other
  • one-to-one described in EF fluent API is basically two one-to-many for both sides of the relationship, which boils that to one-to-one when db is finally created
  • we need to put nullable foreign key on at least one entity.
    That’s important for inserts: EF can’t generate SQL that inserts both entities and sets foreign keys in one db call. So we do the following:
    • first insert one entity, get its primary key (PK),
    • then insert second entity with foreign key from first transaction
    • last transaction is to set first entity foreign key of second entity PK
  • If there’s a simpler or more “correct” solution, please let me know! This is the first approach that worked fine, but I hope there’s an even easier way without one-to-many trick

Here’s working solution in Entity Framework 6.1.2 (probably works with v5 also):

Sample application is available on Github!