Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 348
Ciccio Avatar asked Oct 25 '25 04:10

Ciccio


1 Answers

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);
like image 187
Gert Arnold Avatar answered Oct 26 '25 23:10

Gert Arnold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!