How to setup Entity Framework Code first to have only one side 0 to 1 relationship

Let say you have an entity that can but doesn’t mean will have a relation to another entity. This is a 0..1 to 1 or 0..1 to many.

In this example, we show a scenario where we have one entity that has a relation to a second entity. The second entity doesn’t have any reference to the first one.

At first, we may think than this code below works.

                .HasOptional(d => d.EntityTwo)

The WithOptionalDependent tells EF (Entity Framework) that EntityOne is the one of the two entities that hold the reference which is optional as stated with the HasOptional property. No! This raise an error that tell that it cannot find EntityTwo_ID key. This is problematic because in the scenario we are talking about the foreign key has a special name. So, we have to configure the foreign key. Of course, if your FK is named EntityTwo_ID than you are all fine.

                .HasOptional(d => d.EntityTwo)
                .Map(d => d.MapKey("EntityTwoID");

The HasForeignKey is not available from WithOptionalDependant, but with Map we can setup the foreign key name. Unfortunately, this won’t work either. The error is an invalid column name. From here, we can realise that the MapKey is used by the principal entity and not the dependent.

Still, we want to have 0..1 relation. How can we setup this optional relation ship with Entity Framework without having on the other side the property to the other entity? We need to use HasOption and threat the whole situation not as 0..1 to 1 but 0..1 to many.

                .HasOptional(d => d.EntityTwo)
                .HasForeignKey(d => d.EntityTwoID)

To make it works, we use WithMany without specifying the other side property (since we do not have it) and we use HasForeignKey to specify the correct foreign key. And that’s it! It works!

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

10 thoughts on “How to setup Entity Framework Code first to have only one side 0 to 1 relationship

  1. Hello!
    How can i delete “EntityTwo” in this case?
    I get:

    System.Data.SqlClient.SqlException : The DELETE statement conflicted with the REFERENCE constraint “FK_dbo.EntityOne_dbo.EntityTwo_EntityTwoCode”. The conflict occurred in database “***”, table “dbo.EntityOne”, column ‘EntityTwoCode’.
    The statement has been terminated.

    EntityOne.EntityTwoCode has no required attribute, in is string FK

  2. This was such a crazy issue – and a clear limitation / unsupported scenario of EF.
    Thanks for giving us a solution to try that is completely non-obvious and a hair-pull to chase!

  3. Hi I use this approach with EF6 and it work fine, but when I want include the EntityTwo this don’t load the entity, but the reference in the BD are fine and the key are fine. What could be? Any idea?

  4. So, I am using EF6 on a database i can’t change. I want to do this, but my foreign key is also the primary key on both tables. The result seems to be is that it still tries to use the names Entity1_Id and Entity2_Id. And I do have the column name set on the id properties. if i go back to add the map key thing, it gives me an error saying that the column has already been defined. Any ideas?

  5. Pingback: c# - La cartographie de clé étrangère dans HasOptional().WithOptionalDependent() relation dans l'Entity Framework 6

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.