Wonder
Wonder

Reputation: 1020

Entity that contains itself as ICollection

Using Entity Framework. Simple Page class with tree hierarchy.

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; }
}

Throws an error when I'm trying to add an object and SaveChanges:

Unable to determine the principal end of the 'Models.Page_Parent' relationship. Multiple added entities may have the same primary key.

I roughly understand the problem, but have no idea how to fix it.

Upvotes: 2

Views: 209

Answers (2)

Eranga
Eranga

Reputation: 32447

Make the ParentId property nullable. Root element won't have a parent. Use the fluent configuration as shown in @Jayantha's answer.

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; }
}

Upvotes: 2

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21376

Have you tried defining the relationship?

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

Upvotes: 2

Related Questions