Asp.net mvc 3 将自身包含为ICollection的实体

Asp.net mvc 3 将自身包含为ICollection的实体,asp.net-mvc-3,entity-framework,Asp.net Mvc 3,Entity Framework,使用实体框架。 具有树层次结构的简单页面类 public class Page { public int Id { get; set; } //... public int ParentId { get; set; } //removing this solves the problem, but I would like to keep this line public virtual Page Parent { get; set; } public v

使用实体框架。 具有树层次结构的简单页面类

public class Page
{
    public int Id { get; set; }
    //...
    public int ParentId { get; set; } //removing this solves the problem, but I would like to keep this line
    public virtual Page Parent { get; set; }
    public virtual ICollection<Page> SubPages { get; set; }
}
公共类页面
{
公共int Id{get;set;}
//...
public int ParentId{get;set;}//删除它可以解决问题,但我想保留这一行
公共虚拟页父项{get;set;}
公共虚拟ICollection子页面{get;set;}
}
尝试添加对象并保存更改时引发错误:

无法确定“Models.Page\u Parent”关系的主体端。多个添加的实体可能具有相同的主键


我大致了解这个问题,但不知道如何解决。

您是否尝试过定义这种关系

this.HasRequired(page => t.Parent ).WithMany(t => t.SubPages).HasForeignKey(d => d.ParentId);

使
ParentId
属性为空。根元素将没有父元素。使用流畅的配置,如@Jayantha的回答所示

public class Page
{
    public int Id { get; set; }
    //...
    public int? ParentId { get; set; }  like to keep this line
    public virtual Page Parent { get; set; }
    public virtual ICollection<Page> SubPages { get; set; }
}
公共类页面
{
公共int Id{get;set;}
//...
public int?ParentId{get;set;}要保留此行吗
公共虚拟页父项{get;set;}
公共虚拟ICollection子页面{get;set;}
}