简体   繁体   中英

Entity Framework - relating subclass foreign key to parent class primary key

I want to map the foreign key FormId of class Question from the list Subquestions to the primary key of class Form . Entity Framework is not making this relationship in the sub questions.

My Form class.

public class Form
{
    private readonly ICollection _questions = new List();

    public int Id { get; private set; }
    public string Title { get; private set; }
    public string Description { get; private set; }

    ...
}

My Question class.

public class Question 
{
    private readonly ICollection _subquestions = new List();

    public int Id { get; private set; }
    public string Title { get; private set; }
    public bool Required { get; private set; }
    
    public int? QuestionParentId { get; private set; }
    public Question QuestionParent { get; private set; }

    public int FormId { get; private set; }
    public Form Form { get; private set; }

    ...
}

What should the configuration in IEntityTypeConfiguration look like?

Entity Configuration should be look like this

modelBuilder.Entity<Question>()
            .HasOne(q => q.Form)
            .WithMany(f => f._questions);

modelBuilder.Entity<SubQuestion>()
            .HasOne(s => s.Question)
            .WithMany(q => q._subquestions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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