实体框架6自我加入不填充

时间:2014-12-23 23:41:42

标签: c# entity-framework entity-framework-6

我有以下数据库表:

CREATE TABLE [dbo].[QUESTIONS](
    [QUESTION_ID] [int] IDENTITY(1,1) NOT NULL,
    [QUESTION_TEXT] [varchar](max) NOT NULL,
    [PARENT_QUESTION_ID] [int] NULL,
 CONSTRAINT [PK_QUESTIONS] PRIMARY KEY CLUSTERED 
(
    [QUESTION_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[QUESTIONS]  WITH CHECK ADD  CONSTRAINT [FK_QUESTIONS_QUESTIONS] FOREIGN KEY([PARENT_QUESTION_ID])
REFERENCES [dbo].[QUESTIONS] ([QUESTION_ID])
GO

ALTER TABLE [dbo].[QUESTIONS] CHECK CONSTRAINT [FK_QUESTIONS_QUESTIONS]
GO

基本上PARENT_QUESTION_ID是QUESTION_ID上的自联接。我正在尝试在EF 6.0 Code First中实现它。

在课堂上我有:

[Serializable]
[Table("QUESTIONS")]
public class Question : BaseDomainModel, IQuestion
{
    [Column("QUESTION_ID")]
    public override int? Id { get; set; }

    [Column("QUESTION_TEXT")]
    [Required]
    public string QuestionText { get; set; }

    [Column("PARENT_QUESTION_ID")]
    public int? ParentQuestionId { get; set; }

    public virtual IQuestion Parent { get; set; }

    [ForeignKey("ParentQuestionId")]
    public virtual List<IQuestion> ChildQuestions { get; set; }

    public Question()
    {
        ChildQuestions = new List<IQuestion>();
    }
}

代码执行但ChildQuestions永远不会填充。例如,如果我在数据库中有这个: enter image description here

记录24和25应该填写在问题26的ChildQuestions列表中。相反,没有任何内容出现。

以下是我从存储库填写问题的电话:

public IQuestion GetById(int id)
{
    IQuestion question = null;

    using (var db = new MainContext())
    {
        question = db.Questions.SingleOrDefault(a => a.Id == id);
    }

    return question;
}

以下是我正在使用的上下文:

internal class MainContext : DbContext
{
    internal MainContext() : base("name=ACME.Context") { }

    public virtual DbSet<Question> Questions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<MainContext>(null);

        base.OnModelCreating(modelBuilder);
    }
}

1 个答案:

答案 0 :(得分:0)

您在错误的属性上获得了ForeignKey属性。而不是ChildQuestions,它应该在Parent上:

[ForeignKey("ParentQuestionId")]
public virtual IQuestion Parent { get; set; }

public virtual List<IQuestion> ChildQuestions { get; set; }