Home » Ado.Net » Entity Framework » How to setup Entity Framework Code first to have only one side 0 to 1 relationship

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.

            modelBuilder
                .Entity<EntityOne>()
                .HasOptional(d => d.EntityTwo)
                .WithOptionalDependent();

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.

            modelBuilder
                .Entity<EntityOne>()
                .HasOptional(d => d.EntityTwo)
                .WithOptionalDependent()
                .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.

            modelBuilder
                .Entity<EntityOne>()
                .HasOptional(d => d.EntityTwo)
                .WithMany()
                .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 Responses so far.

  1. Diego Doná says:

    Thanks, it was very useful to me =)

  2. Artur Cruz says:

    Thank you!

    This was a life saver!

  3. Sumant says:

    Thanks so much was searching for this solution for like 2 days.

  4. Robby says:

    Wow, thanks for this. I could not figure this out until I read your post.

  5. Except says:

    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

  6. 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!

  7. wale A says:

    lol, found this solution in 2017. thanks a lot!

  8. Zwei says:

    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?

  9. Justin says:

    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?

  10. […] À droite, vous devez dire à EF comment faire de l'association avec HasForeignKey ou MapKey. patrickdesjardins.com/blog/… Merci pour l'aide. Le problème avec HasForeignKey est qu'il est uniquement disponible en WithMany […]

Leave a Reply to wale A Cancel 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.