在c#中为c#中的递归嵌套对象创建EF映射器配置

时间:2013-09-17 08:32:27

标签: c# linq entity-framework-4 linq-to-entities

我正在使用visual studio 2010 .Net4。

我在尝试使用EF为数据库配置映射器时遇到问题。

这是我要映射的类,我正在尝试映射它,以便我可以使用include语句根据列表中的Question对象的ParentID属性填充子列表。

public class Question
{
    public int QuestionId { get; set; }
    public int ParentId { get; set; }
    public string QuestionText { get; set; }
    public string Answer { get; set; }

    //recursive list of Questions
    public virtual List<Question> Children {get; set;}
}

这是我尝试配置映射器

class QuestionConfiguration : EntityTypeConfiguration<Question>
{
    public QuestionConfiguration()
        : base()
    {
        this.HasKey(x => x.QuestionId);

        this.Property(p => p.ParentId)
            .HasColumnName("ParentId");

        this.Property(p => p.QuestionText)
            .HasColumnName("QuestionText");

        this.Property(p => p.Answer)
            .HasColumnName("Answer");

        this.HasMany(w => w.Children)
            .HasForeignKey(w => w.ParentId);

        ToTable("tbl_Questions");
    }
}

我仍然是EF和c#的新手,所以我不确定如何从这里开始。我上面的尝试甚至都没有编译。

任何正确方向的帮助或指示都会有很大的帮助。

1 个答案:

答案 0 :(得分:0)

你很亲密:

this.HasMany(w => w.Children)
    .WithOptional() // Added this
    .HasForeignKey(w => w.ParentId);

唯一的问题是,我认为ParentId应该是一个可以为空的int,因为层次结构的根永远不会有父。