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

.net-core-2.0 c# entity-framework-core

Question

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??

    }
}
1
1
5/14/2018 5:01:41 PM

Accepted Answer

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)

3
5/14/2018 5:00:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow