How to Get Nested Structure Using EF Core 7 TPC

193 views Asked by At

I have base abstract class:

public abstract class PossibleAnswerBase
{
    public Uuid Id { get; protected set; }
    public string Title { get; protected set; }

    #region Navigation

    public Uuid QuestionId { get; protected set; }
    public Question Question { get; }
        
    public Uuid? ParentId { get; protected set; }
    public PossibleAnswerCategory Parent { get; }
        
    #endregion

    protected PossibleAnswerBase()
    {
    }
}

Two classes derives from it. The first one PossibleAnswerCategory could have nested structure:

public class PossibleAnswerCategory : PossibleAnswerBase
{
    public ICollection<PossibleAnswerBase> PossibleAnswers { get; private set; }

    public PossibleAnswerCategory(Uuid id, Uuid? parentId, string title)
    {
        Id = id;
        Title = title;
        ParentId = parentId;
    }

    [UsedImplicitly]
    private PossibleAnswerCategory()
    {
    }
}

public class PossibleAnswer : PossibleAnswerBase
{
    public PossibleAnswer(Uuid id, string title, Uuid? parentId)
    {
        Id = id;
        Title = title;
        ParentId = parentId;
    }
}

I've configured context like this:

private void MapQuestionPossibleAnswerBase(ModelBuilder modelBuilder)
{
    var builder = modelBuilder.Entity<PossibleAnswerBase>()
        .UseTpcMappingStrategy();
    builder.HasKey(r => r.Id);

    builder.Property(r => r.Id).HasColumnName("Id");
    builder.Property(r => r.Title).HasColumnName("Title");
    builder.Property(r => r.QuestionId).HasColumnName("QuestionId");
    builder.Property(r => r.ParentId).HasColumnName("ParentId");
            
    builder.HasOne(pa => pa.Question)
        .WithMany(q => q.PossibleAnswers)
        .HasForeignKey(pa => pa.QuestionId);

    builder.Navigation(pa => pa.Question).AutoInclude();
}

private void MapQuestionPossibleAnswerCategory(ModelBuilder modelBuilder)
{
    var builder = modelBuilder.Entity<PossibleAnswerCategory>()
        .UseTpcMappingStrategy().ToTable("violation_categories");

    builder.HasMany(w => w.PossibleAnswers)
        .WithOne(w => w.Parent)
        .HasForeignKey(w => w.ParentId);
}

private void MapQuestionPossibleAnswers(ModelBuilder modelBuilder)
{
    var paBuilder = modelBuilder.Entity<PossibleAnswer>()
        .UseTpcMappingStrategy().ToTable("violations");
}

I want to get collection of PossibleAnswerCategory which will contain collection of PossibleAnswer (in ICollection PossibleAnswers). But when I make query PossibleAnswers is empty: PossibleAnswers is null

How configure context to fill PossibleAnswers collection?

0

There are 0 answers