如何使用实体框架存储相同模型的子项?

时间:2013-07-09 17:07:22

标签: entity-framework ef-code-first

我有模特页面:

public int Id{ get; set; }
public string Name { get; set; }

我想在那儿有儿童页面:

public int Id{ get; set; }
public string Name { get; set; }
public List<Page> Childrens { get; set; }

设置同一型号的非必需儿童用品的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我的方式需要在模型中添加一些其他属性(我使用virtual`关键字作为导航属性,因为我需要延迟加载):

public class Page
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentID { get; set; } // Nullable int because your Parent is optional.

    // Navigation properties
    public virtual Page Parent { get; set; } // Optional Parent
    public virtual List<Page> Children { get; set; }
}

然后,使用外键关联,您可以像这样配置关系(这是我的Page映射):

// You may be configuring elsewhere, so might want to use `modelBuilder.Entity<Page>()` instead of `this`

this.HasMany(t => t.Children)
    .WithOptional(t => t.Parent)
    .HasForeignKey(x => x.ParentID);

基本上,每个孩子都知道它的父母,并且由于导航属性,你可以探索双方的关系。