EF核心一对多回到同一实体

时间:2018-12-10 20:36:49

标签: ef-code-first asp.net-core-mvc ef-core-2.1

我有一个实体SubQuestion,它可以与零个,一个或多个其他子问题有关。我正在尝试使用EF Core对此建模。这是我到目前为止提出的设计。

实体

public class SubQuestionRelated
{
    public int SubQuestionId { get; set; }
    public SubQuestion SubQuestion { get; set; }
    public int RelatedToSubQuestionId { get; set; }
    public SubQuestion RelatedToSubQuestion { get; set; }
}

public class SubQuestion
{
    public int Id { get; set; }
    public List<SubQuestionRelated> RelatedSubQuestions { get; set; } = new List<SubQuestionRelated>();
    public SubQuestionRelated DontUse { get; set; }
    // other properties not relevant...
}

OnModelCreating配置

 modelBuilder.Entity<SubQuestionTPCalc>()
            .HasKey(sqtpc => new { sqtpc.SubQuestionId, sqtpc.RelatedToSubQuestionId });

 modelBuilder.Entity<SubQuestionTPCalc>()
            .HasOne(sqtpc => sqtpc.SubQuestion)
            .WithOne(sq => sq.DontUse)
            .OnDelete(DeleteBehavior.Restrict);

 modelBuilder.Entity<SubQuestionTPCalc>()
            .HasOne(sqtpc => sqtpc.RelatedToSubQuestion)
            .WithMany(sq => sq.RelatedSubQuestions)
            .HasForeignKey(sqtpc => sqtpc.RelatedToSubQuestionId);

问题

return _dbContext.Questions
                        .Include(q => q.SubQuestions)
                        .ThenInclude(sq => sq.RelatedSubQuestions)
                        .ToList();

问题是当我去查询该数据时,EF Core将不会加载“相关子问题”。我猜有一些默认行为可以防止循环引用?我要EF Core做的是向RelatedSubQuestion表的LEFT JOIN。

UPDATE

EF Core提出了相关子问题,但它加入了错误的领域。它正在从SubQuestion加入RelatedToSubQuestionId,而我想从SubQuestion加入SubQuestionId ...

0 个答案:

没有答案