Gabriel Santos Lemos
Gabriel Santos Lemos

Reputation: 59

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?

Upvotes: 0

Views: 236

Answers (1)

Bin Rohan
Bin Rohan

Reputation: 352

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);

Upvotes: 0

Related Questions