简体   繁体   English

如何在实体框架核心中映射一对多的可选递归关系

[英]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, ie Collection I am struggling to map this in my model configuration class. 我有实体调用Answers,而答案实体可以有多个子答案,即Collection我正在努力将其映射到我的模型配置类中。

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

    }
}

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. 其余部分取决于模型中逆导航属性和显式FK属性的存在。

(A) The original model (no inverse navigation property, no explicit FK property) (A)原始模型(无逆向导航属性,无显式FK属性)

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

(B) With inverse navigation property added to the model (B)在模型中添加了反向导航属性

public virtual AnswerDataModel Parent { get; set; }

it would be: 这将是:

.WithOne(answer => answer.Parent);

(C) With explcit FK property added to the model (C)在模型中添加了明显的FK属性

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 (D)在模型中同时添加了反向导航和显式FK属性

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) (这里的HasForeignKey可以跳过,因为它是约定俗成的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM