3

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.

Simone
  • 2,304
  • 6
  • 30
  • 79

1 Answers1

4

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);
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • Thank you for you answer... yes, now it's clearer... just one doubt... perhaps should be: `.HasOne(x => x.ChildEntity).WithOne(x => x.ParentEntity)` instead of `.HasOne(x => x.ParentEntity).WithOne(x => x.ChildEntity)`? This self-reference make me confusion... – Simone Dec 24 '21 at 22:54
  • 1
    It doesn't make a difference for the data model, or anything actually. – Gert Arnold Dec 25 '21 at 08:05