Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map one to many optional recursive relationship in Entity Framework core

I have entity call Answers and answer entity can have multiple child answers, i.e. Collection I am struggling to map this in my model configuration class.

Model Class

public class AnswerDataModel : IDataModel<Guid>
{
    public AnswerDataModel()
    {

        SubQuestionAnswers = new HashSet<AnswerDataModel>();
    }
    public Guid Id { get; set; }

    public Guid QuestionId { get; set; }

    public string Value { get; set; }

    public virtual ICollection<AnswerDataModel> SubQuestionAnswers { get; set; }
}

Answer Configuration class

public class AnswerEntityConfiguration : IEntityTypeConfiguration<AnswerDataModel>
{
    public void Configure(EntityTypeBuilder<AnswerDataModel> builder)
    {
        builder.ToTable("Answers");
        builder.HasKey(answer => answer.Id);

        builder
            .HasOne(answer => answer.Question)
            .WithMany(question => question.Answers)
            .HasForeignKey(answer => answer.QuestionId);

       builder
             .????????  // how to map recursive Answer Collections as subQuestionAnswer??

    }
}
like image 272
K.Z Avatar asked Oct 27 '25 09:10

K.Z


1 Answers

You start with the collection navigation property:

builder
    .HasMany(answer => answer.SubQuestionAnswers)

The rest depends of the presence of the inverse navigation property and explicit FK property in the model.

(A) The original model (no inverse navigation property, no explicit FK property)

.WithOne()
.HasForeignKey("ParentId")
.IsRequired(false);

(B) With inverse navigation property added to the model

public virtual AnswerDataModel Parent { get; set; }

it would be:

.WithOne(answer => answer.Parent);

(C) With explcit FK property added to the model

public Guid? ParentId { get; set; }

it would be:

.WithOne()
.HasForeignKey(answer => answer.ParentId);

(D) With both inverse navigation and explcit FK properties added to the model

public virtual AnswerDataModel Parent { get; set; }
public Guid? ParentId { get; set; }

it would be:

.WithOne(answer => answer.Parent)
.HasForeignKey(answer => answer.ParentId);

(HasForeignKey here can be skipped because it's by convention)

like image 129
Ivan Stoev Avatar answered Oct 29 '25 00:10

Ivan Stoev



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!