entity-framework-coreone-to-oneself-referencing-table

Self referencing / parent-child relationship one-to-zero or one in Entity Framework Core


I want to create a referencing / parent-child relationship one-to-zero or one in Entity Framework Core. I mean that my entity could have a parent:

public class MyEntity
{
    public Guid Id { get; set; }

    public Guid? ParentEntityId { get; set; }
    public MyEntity ParentEntity { get; set; }

    public MyEntity ChildEntity { get; set; }
}

I am trying to configure it via fluent api:

entity.HasOne(x => x.ParentEntity)
    .WithOne(x => x.ChildEntity)
    .HasForeignKey( .... )

I do not understand what I do have to write in the last line. I am not either sure my entity is correct.

Can anyone help me please?

EDIT: This question does not resolve my problem: Self referencing / parent-child relationship in Entity Framework My problem is about create the foreign key. This line does not work:

.HasForeignKey(x => x.ParentEntityId)

HasForeignKey expects a string in input.


Solution

  • In a one-to-one relationship you always have to specify the dependent entity type in the HasForeignKey call, i.e. the entity that will contain the foreign key. For a one-to-one relationship between two different classes that makes sense, see the standard EF example. For a self-reference it looks obvious that EF should figure out there's no option. Still, you have to specify the type:

    modelBuilder.Entity<MyEntity>()
        .HasOne(x => x.ParentEntity)
        .WithOne(x => x.ChildEntity)
        .HasForeignKey<MyEntity>(c => c.ParentEntityId);