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.
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; }
}
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??
}
}
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)