如何在 Entity Framework 核心中映射一对多可选递归关系

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

我有实体调用答案,答案实体可以有多个子答案,即集合我正在努力将其映射到我的模型配置中 class。

型号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; }
}

答案配置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??

    }
}

您从 collection 导航开始 属性:

builder
    .HasMany(answer => answer.SubQuestionAnswers)

其余部分取决于模型中是否存在反向导航 属性 和显式 FK 属性。

(A) 原始模型(无逆向导航属性,无显式FK属性)

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

(B) 将反向导航 属性 添加到模型中

public virtual AnswerDataModel Parent { get; set; }

它将是:

.WithOne(answer => answer.Parent);

(C) 将显式 FK 属性 添加到模型中

public Guid? ParentId { get; set; }

它将是:

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

(D) 向模型中添加了反向导航和显式 FK 属性

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

它将是:

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

(HasForeignKey这里是约定俗成可以跳过)